Animation works, but Unity doesn't realize it I have an animation which plays once, and it played once just fine. I want to Invoke a method as soon as the animation finishes. I have been researching and experimenting for over an hour now, but without the result I want. I try to get the animation from the Animator, but Unity says my animation is not attached. The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it. How can I achieve this? Here is the code which results in the error CODE using UnityEngine using System.Collections RequireComponent(typeof(PolygonCollider2D)) RequireComponent(typeof(Animator)) public class Construction MonoBehaviour Use this for initialization void Start() Invoke("EnableObstacleState", GetComponent lt Animator gt ().animation.clip.length) private void EnableObstacleState() GetComponent lt PolygonCollider2D gt ().enabled true ERROR MissingComponentException There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it. You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it. Construction.Start () (at Assets Scripts Construction.cs 11)


How to Create a Blast of Liquid in Unity I am making a small cartoon ish fighting game, and one of the weapons is a Hot Coffee Sprayer, which is a shotgun style weapon. How do I create a thick blast of dark liquid to come from it, with a solid appearance like the repulsion gel in Portal 2? If its too complex, just tell me how make the gun launch a handful individual drops at once rather than a horizontal wall of coffee. I am not amazing in Unity or C but I learn easily and I understand the fundamentals of programming very well. I'm skilled in Python.


Random.range giving me the same value at the same time I created a random direction in x and y axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y axis. How do I not let this happen, I only want one axis to have a value, not both? ERROR HOW I WANT IT TO HAPPEN CODE public Vector2 randomDirection void Awake() void Update() randomDirection new Vector2(Random.Range( 1, 2), Random.Range( 1, 2))


Help with modifying a geometry grass shader to allow removing areas? So I have this geometry grass shader from a roystan tutorial I followed but it applies the grass effect to the entire mesh at once. I need to find a way to only apply grass to set areas much like how the unity painting vegetation tools work. I had an idea of using a quot guiding quot texture that the shader would follow which would only apply grass onto set areas on the texture e.g areas that are green but I'm not sure how to implement it. I would appreciate any advice!


Scene dark when perspective camera is far from scenery I can't find anything about this subject in the docs or forums to know if this is normal behavior There seems to be a direct correlation between how close to the scenery my camera gets and how brightly lit the scene is. My camera is able to move up to 200 units from Vector3.zero. Here are two shots of the same piece of scenery one close up, one far away The camera is set to perspective, using deferred rendering. Things I've tried Turning off post processing Using auto expose in post processing Changing to orthographic (removes the issue, scene is uniformly bright at any distance) Changing the FOV Changing global lighting to use color rather than skybox Putting some lights at altitude This may be normal behavior amp I just havent noticed before. Can anyone confirm? Is there some way to prevent this happening? I don't want to use an orthographic camera but I do want the scene to be evenly bright at any distance from the camera.


Function Not Storing New Value of Variables? I'm currently building a small scope RPG and running into an issue with modifying variables. My goal is to alter my character's stats when I run a procedure to change their equipment. My code is as follows public class Player MonoBehaviour Base stat variables public static int PAtk 12 public static int PDef 6 Battle exclusive stats. Will have equipment added onto them. public static int Attack PAtk public static int Defense PDef Equipment variables. public string weapon public string armor private void Awake() Get equipment EquipWeapon( quot Bronze Sword quot ) EquipArmor( quot Bronze Armor quot ) void EquipWeapon(string WeaponName) weapon WeaponName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName) void EquipArmor(string ArmorName) armor ArmorName EquipmentManager.GetComponent lt Equipment gt ().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName) public class Equipment MonoBehaviour Create dictionary to give each weapon a key ID. This will be used for calling items in another array. Dictionary lt string, int gt WeaponDictionary new Dictionary lt string, int gt () Create weapon array for stats. public int , WeaponStats Start is called before the first frame update void Awake() Declare weapon IDs WeaponDictionary.Add( quot Bronze Sword quot , 0) WeaponDictionary.Add( quot Bronze Armor quot , 1) Declare stat array Table ID, Atk, Def WeaponStats new int , 0,4,0 , 1,0,4 public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment) BattleAtk BaseAtk WeaponStats WeaponDictionary Equipment , 1 Debug.Log(BattleAtk quot Battle Power quot ) BattleDef BaseDef WeaponStats WeaponDictionary Equipment , 2 Debug.Log(BattleDef quot Battle Defense quot ) The general gist of it is once EquipWeapon or EquipArmor is ran, the equipment variables in the Player class will be updated. Afterwards, another function in the Equipment class will be ran with variables from the Player class passed over, in order to be modified by the WeaponStats array. The Debug logs in EquipStatIncrease show me that I am getting the desired results. However, the Attack parameter that is being placed into the function is not being permanently modified. During the first execution of the EquipStatIncrease method, I will get a result of 16 BattleAtk and 6 BattleDef, due to the weapon being equipped. However, once it's run a second time to equip the armor, I'm shown a result of 12 BattleAtk and 10 BattleDef, even though BattleAtk should have stayed at 16. This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this. In the EquipStatIncrease parameters, BattleAtk gives the message Parameter 'BattleAtk' can be removed if it is not part of a shipped public API its initial value is never used However, I don't know what action to take to resolve this. I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable. If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases BattleAtk and BattleDef), then I don't see how an int function would work.


How do I get parabolic movement in Unity using Rigidbody2d? EDIT It was the Animator after all. Apply Root Motion basically nullifies any physics based work. I "know" this answer but I can't figure out what can possibly be wrong. My code is in FixedUpdate(). My Rigidbody2D has a Gravity Scale of 4 and a Mass of 1. For whatever reason a Gravity Scale of 1 just isn't strong enough to keep it from floating away. In the pictures below the little cubes should be marking each frame. Using the below code I get a jagged leap movement. The object shoots upwards and falls like a feather. if(Game.inputManager.GetKey("Jump").KeyPressed()) yForce 1000f this.rigidbody2D.AddForce(Vector2.up yForce) And using another suggestion I distribute the force over a second of time. if(Game.inputManager.GetKey("Jump").KeyPressed()) addForceTimer 1 yForce 1000f addForceTimer Time.deltaTime if(addForceTimer gt 0) this.rigidbody2D.AddForce(Vector2.up yForce Time.deltaTime 4) And I get a more desirable but still just as wrong movement where there is no hang at the top of the jump. From what I thought I knew neither of these should be happening at all. The object shouldn't be falling at a constant speed like it is. Does anybody have any suggestions? The character is animated if that can possibly have some sort of effect but I don't imagine it would.


How do I fix missing anti aliasing in the Unity scene view and game? Both the editor and the game seem to lack anti aliasing even though quality is set to Ultra. I chose the quot 3D quot project template when I created the project, so I am using the build in render pipeline.


First object jumps on re entry of second colliding object The scenario is that I have two objects Object A and Object B. The Object A is lying on the ground and when Object B enters the collider of Object A, the Object A moves (only X and Z axis) with Object B. The movement works well with the script shown below. The issue is that most of the time, the Object A's initially position shifts by few meters whenever Object B enters its collider. I feel it is related to offset position. What should happen is that, Object A should be the same position when Object B enters the collider and move along with Object B only when Object B moves. So how do I fix this? private Vector3 offsetPosition public Transform ObjectB public bool ObjectB Collision false void Start () offsetPosition ObjectB.transform.position this.transform.position void ObjectB HasEntered() offsetPosition ObjectB.transform.position this.transform.position Update is called once per frame void LateUpdate () if (ObjectB Collision true) this.transform.position new Vector3 (ObjectB.transform.position.x, this.transform.position.y, ObjectB.transform.position.z) new Vector3 (offsetPosition.x, 0, offsetPosition.z) public void OnTriggerEnter (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB HasEntered() ObjectB Collision true public void OnTriggerExit (Collider col) if (!enabled) return if (col.gameObject.name quot Object B quot ) ObjectB Collision false


Unity ECS How do I stop an entity from spawning twice? I am implementing a flight dynamics model using Unity's built in ECS package, Entities, and I keep running into one particular issue where the aircraft I'm trying to spawn gets converted into an entity twice. Essentially, I have a singleton Monobehaviour that handles setting up the aircraft entity from a GameObject Prefab. Here's the script public class GameManager MonoBehaviour private BlobAssetStore blobAssetStore public static GameManager main public GameObject planePrefab public float zBound 0.0f public float throttleMaxBound 1.0f public float alphaMaxBound 20.0f public float bankMaxBound 20.0f public float flapMaxBound 40.0f public float throttleMinBound 0.0f public float alphaMinBound 0.0f public float bankMinBound 20.0f public float flapMinBound 0.0f public State state public Properties prop Entity planeEntityPrefab EntityManager manager private void Awake() if (main ! null amp amp main ! this) Destroy(gameObject) return main this manager World.DefaultGameObjectInjectionWorld.EntityManager blobAssetStore new BlobAssetStore() GameObjectConversionSettings settings GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore) planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) SpawnEntity() private void OnDestroy() blobAssetStore.Dispose() void SpawnEntity() Entity plane manager.Instantiate(planeEntityPrefab) prop new Properties( 16.2f, 10.9f, 2.0f, 0.0889f, slope of Cl alpha curve 0.178f, intercept of Cl alpha curve 0.1f, post stall slope of Cl alpha curve 3.2f, post stall intercept of Cl alpha curve 16.0f, alpha when Cl Clmax 0.034f, parasite drag coefficient 0.77f, induced drag efficiency coefficient 1114.0f, 119310.0f, 40.0f, revolutions per second 1.905f, 1.83f, propeller efficiency coefficient 1.32f propeller efficiency coefficient ) state new State( 0.0f, time 0.0f, ODE results 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, roll angle 4.0f, pitch angle 0.0f, throttle percentage 0.0f flap deflection ) float3 position new float3(state.q1, state.q3, state.q5) manager.SetComponentData(plane, new Translation Value position ) After a little bit of commenting here and there, I was able to determine that the following two lines are responsible for creating two separate entities, though the latter is the only one I'm capable of manipulating using the system. It's also worth mentioning that these two entities are virtually identical in the Entity Debugger, except for the fact that the first entity contains the quot prefab quot tag. planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) and... Entity plane manager.Instantiate(planeEntityPrefab) Is there a way to spawn this entity without both showing up in the debugger or is this unavoidable? If not, is there a way to remove the entity with the quot prefab quot tag from the world? Thanks! )


Method subscribed to an event is called twice for every time the event is raised I am trying to make an inventory system in Unity with ScriptableObjects and a text driver that displays the contents of an inventory. So far the code looks like this An InventoryObject is defined as having a quot Container quot List of ItemObjects (simple scriptable objects, they just have a little information on the object as its sprite, its name, and whether or not it is stackable) and some methods to properly add or remove items (taking item stacking into account) from that list. https pastebin.com t4P3aGmi A PlayerInventory is a script that will be carried by the player's character. It contains a method for adding items collided with to its assigned InventoryObject instance. It also contains an OnItemPickedUp event that takes its InventoryObject instance as a parameter and passes it to listeners like UpdateDisplay. OnItemPickedUp is raised whenever a collision with a compatible item happens. https pastebin.com RsV7XYPp An UpdateDisplay script that listens to the OnItemPickedUp event and subscribes the ProcessInventoryToSingleString(InventoryObject inventory) method, that subsequently calls several methods to transform the contents of the InventoryObject's Container list into a single, formatted string. https pastebin.com N0nsvcWH The items are represented by giving a GameObject with a collider2D, aSpriteRenderer and script that contains the particular ItemObject's data and sets its SpriteRenderer's sprite to the ItemObject's. The problem I'm having is that the method subscribed to the event is being called more than once for each time the event is raised. as shown by the debug logs. Sometimes it's called twice, sometimes even four. This results in my UI display showing more items than there are. https files.catbox.moe afa467.mp4 https files.catbox.moe 6oxh9b.mp4 Here are pictures of the console debug logs I appreciate any help. EDIT These errors also appear. I'd like to believe that they're unrelated.


Most efficient way to modify character mesh at run time What is the most efficient way in unity to alter the mesh of a character in this scenario When the player pick up an item A part of the mesh should be replaced, for example, the left arm is swapped by a robotic, rock, wood etc... arm. The animations are the same. Other parts may change in a different way, for example, left arm stone right wood.(This happens in a different pick up later) There is no problem if the game slows for a sec as this not happen "in action". One more thing In general terms, what are the thing to consider when doing these modifications in terms of performance?(Such as polygons of the mesh, resolution of textures...) Will many changes end up in consuming memory or other resources?


How can I reduce a bezier curve using a slider till all points converge to it's original midpoint I am using the code from the question here to create bezier curves (I didn't think it was necessary to repost the code here since I haven't made any significant changes to it yet). I have a symmetric bezier curve (please see image) that I want to reduce till all points converge at the midpoint of the original curve. I would like to preserve it's symmetry while it moves. I would like achieve this using a float slider (with values from 0 to 1) in editor mode.


Unity Trail for Eyes 2D i want to make some kind of an Eye Tail effect for this charakter I found the Unity Trail Renderer effect but the start of the Trial is perpendicular to the dragged moved direction Can i make the start of the Trail look like the eye block of the charakter? So that if he move left or right, the Trail is only as width as the Eyes height and if the moves up or down, the Trail is correspondingly width. Or is there a better method for making a cool Eye Tail effect?


Draw trajectory arc predictor in game I found this tutorial on youtube and it works pretty well, but I want to add more to it. How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)? Here is the code public class BallLauncher MonoBehaviour public Rigidbody ball public Transform target public float h 25 public float gravity 18 public bool debugPath void Start() ball.useGravity false void Update() if (Input.GetKeyDown (KeyCode.Space)) Launch () if (debugPath) DrawPath () void Launch() Physics.gravity Vector3.up gravity ball.useGravity true ball.velocity CalculateLaunchData ().initialVelocity LaunchData CalculateLaunchData() float displacementY target.position.y ball.position.y Vector3 displacementXZ new Vector3 (target.position.x ball.position.x, 0, target.position.z ball.position.z) float time Mathf.Sqrt( 2 h gravity) Mathf.Sqrt(2 (displacementY h) gravity) Vector3 velocityY Vector3.up Mathf.Sqrt ( 2 gravity h) Vector3 velocityXZ displacementXZ time return new LaunchData(velocityXZ velocityY Mathf.Sign(gravity), time) void DrawPath() LaunchData launchData CalculateLaunchData () Vector3 previousDrawPoint ball.position int resolution 30 for (int i 1 i lt resolution i ) float simulationTime i (float)resolution launchData.timeToTarget Vector3 displacement launchData.initialVelocity simulationTime Vector3.up gravity simulationTime simulationTime 2f Vector3 drawPoint ball.position displacement Debug.DrawLine (previousDrawPoint, drawPoint, Color.green) previousDrawPoint drawPoint struct LaunchData public readonly Vector3 initialVelocity public readonly float timeToTarget public LaunchData (Vector3 initialVelocity, float timeToTarget) this.initialVelocity initialVelocity this.timeToTarget timeToTarget I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode


Why aren't my Unity rotations working properly? I'm experiencing a rather annoying bug and I was hoping someone could offer some help because this just isn't making sense to me. I have a Ballistic script that tells the bullet to move in its local forward direction, which should be whichever way the gun is pointing. I have a PlayerAttack script that calls for a bullet to spawn with OnShootEnter(). It sets the bullets position to that of a bulletSpawn transform, which is a child of the gun. OnShootEnter() is being properly called and bulletSpawn is properly assigned and yet, when the bullet spawns, its facing Vector3.forward, instead of it facing bulletSpawn.forward. These are the only two scripts affecting the bullets spawn, rotation, and direction. Everything looks in order to me what am I missing? public class PlayerAttack MonoBehaviour public GameObject bulletPrefab public Transform gun public Transform bulletSpawn public float damage void OnShootEnter() GameObject bullet Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) public class Ballistic MonoBehaviour public GameObject model public float range public float accuracy public float speed Vector3 dir Vector3.zero void Start () model.transform.SetParent (this.transform) dir transform.forward void Update () transform.GetComponent lt Rigidbody gt ().velocity dir.normalized speed range Time.deltaTime if (range lt 0) Destroy (this.gameObject)


How to turn the hotspot on automatically in Unity? I have made a simple LAN multi player game in Unity (just for learning purposes). This is the main code (for connection) using UnityEngine using System.Collections public class StartServer MonoBehaviour public Transform Makan public Transform CubeOBJ public string SSS void OnGUI () GUILayout.Box (Network.player.ipAddress) if (Network.peerType NetworkPeerType.Disconnected) SSS GUILayout.TextField (SSS) if (GUILayout.Button ("StartServer")) Network.InitializeServer(10, 25000) if (GUILayout.Button ("Connect")) Network.Connect (SSS, 25000) else if (GUILayout.Button ("creatCube")) Network.Instantiate (CubeOBJ, Makan.transform.position, Makan.transform.rotation, 0) It works good. The problem is that in mobile devices I should turn on hotspot by myself for one of the devices. How can I do this automatically from code?


Moving panel between two positions smoothly? I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script public GameObject gunsWindow private Vector3 a, b public bool open use inspector void Start() a gunsWindow.transform.position b new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z) void Update() if(open) gunsWindow.transform.position Vector3.MoveTowards(a, b, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(a, b, Time.deltaTime) panel shaking else gunsWindow.transform.position Vector3.MoveTowards(b, a, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(b, a, Time.deltaTime) shaking


When updating to Universal Render Pipeline an Error occurs I updated to the Universal Render Pipeline and despite of using the auto upgrade from project an error messages appears in the console. Here is the error In order to call GetTransformInfoExpectUpToDate, RendererUpdateManager.UpdateAll must be called first. UnityEngine.Rendering.RenderPipelineManager DoRenderLoop Internal(RenderPipelineAsset, IntPtr, AtomicSafetyHandle)


Can I use different Tile Sprite Sizes on the same Tilemap? My partner and I are creating a 2D RPG with D amp D elements with Unity. I am very new to Unity and making games in general, apart from 2 games which I created with Java and the rougelike tutorial which I did with Unity. For this university project we have 4 months and my partner has the job creating tiles, sprites, sound and music. I will program the game. My question is Can we create 32x32 tiles and 64x64 sprites in the same tilemap or does everything need to be the same size? If we can combine them, will a 64x64 sprite on a 32x32 tilemap take 4 tiles, or can we scale it down to one tile?


Unity DontDestroyOnLoad FindObjectsOfType(GetType()).Length is always returning 1 I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs. This answer suggests the following code public void Awake() DontDestroyOnLoad(this) if (FindObjectsOfType(GetType()).Length gt 1) Destroy(gameObject) Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy. I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.


Button mapping of an Xbox 360 controller for windows I can't get a clear answer on the rest of the internet. What are the joystick buttons for left and right triggers? I'm on Windows, if it matters.


Unity3D Download multiple files and implement a callback IEnumerator GetFileRequest(List lt String gt urlList, Action lt List lt UnityWebRequest gt gt callback) List lt UnityWebRequest gt reqList new List lt UnityWebRequest gt () for (int i 0 i lt urlList.Count i ) using (UnityWebRequest req UnityWebRequest.Get(urlList i )) req.downloadHandler new DownloadHandlerFile(GetFilePath(urlList i )) reqList.Add(req) yield return reqList callback(reqList) I'm using this code, all files get downloaded, but they seem to be corrupted ( I guess it's not completely downloaded). How do I complete the download without files getting corrupted?


Unity 2.5D Character Movement I'm wondering if anyone can point me in the right direct as to how to take a 2D character sprite in Unity and have said character turn corners in a 3D style. Solutions or resources welcome.


Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.


How to mitigate when applying horizontal force to a rigidbody seems to overpower gravity? I've started testing movement using the example code in this answer of making a body accelerate to a target velocity private void FixedUpdate() Vector2 input GetInput() if (Mathf.Abs(input.x) gt float.Epsilon Mathf.Abs(input.y) gt float.Epsilon) Vector3 desiredVelocity new Vector3(input.x speed, 0f, input.y speed) Vector3 delta desiredVelocity body.velocity Vector3 acceleration delta Time.deltaTime if (acceleration.sqrMagnitude gt maxAccel maxAccel) acceleration acceleration.normalized maxAccel body.AddForce(acceleration, ForceMode.Acceleration) and I've encountered the following curious behavior https imgur.com snGyVYK When moving the body by applying force, the body seems to levitate as if gravity is not being applied. It actually is being applied but it seems as if the force being applied to the body is overriding the force of gravity because as soon as I let go of the movement keys the body suddenly drops. I am not applying any force on the y axis so I'm not sure what exactly is at play here. What is going on here and what can I do to mitigate this behavior?


When importing Mixamo animated characters into Unity, they come without avatar? I'm using Unity 2019.3.3f1. I create the character in Adobe Fuse. I uploaded it to Mixamo and choose an animation. I then downloaded the fbx for unity file. When imported into Unity, it is visible that the file has no avatar or animator component. How can I fix this? Is it a Unity version issue?


Custom node editor in Unity Im currently making a game on unity, and in the game i want to make quest system to be flexible, as the game world is generated randomly. I also want to make it easy to create quests for myself and possibly modders. So i want to make a menu for creating quests, however i couldnt find any info on how to make node editor window in unity(like shader graph, vfx graph, etc.). How do I do this?


How do I blink a sprite a few times before it disappears? I need the 3d poop emoji model in the chest on the right to blink, visible invisible visible, several times This is a 3d gameObject oriented to face the camera, shaded with an unlit material. I need the object to "blink flash" to indicate that the item has been obtained. The object needs to be generated the moment the lid opens (done), stay unchanged until the lid pops all the way up (0.2 seconds), and flash 3 times during the 0.6 seconds the lid is up. The object is destroyed the moment the lid starts to come down again. My code (blinking flashing is not working) using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject item null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") Update is called once per frame void Update() void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(item, transform.position new Vector3(0, 0.5f, 0), Camera.main.transform.rotation Quaternion.Euler(0,180,0)) Blink(itemClone) Destroy(itemClone) disabled true IEnumerator Blink(GameObject obj) Renderer objRenderer obj.GetComponent lt Renderer gt () objRenderer.enabled true yield return new WaitForSeconds(0.2f) for (int i 0 i lt 3 i ) objRenderer.enabled false yield return new WaitForSeconds(0.1f) objRenderer.enabled true yield return new WaitForSeconds(0.1f) Instead of blinking flashing, the object is just there, doing nothing.


Unity 5.1 Asset bundle for windows I am working on the asset bundle method, i know how to use the asset bundle for untiy 4.x series but i am trying to do this in unity5. I heard in unity 5 is more compatibility to do. I searched in youtube and google but i didnt get the proper tutorial to how to use that. So please suggest me or provide some tutorial to do this. Thanks in Advance.


How can I use a coroutine and GetAxis to rotate a game object? For the sake of learning about coroutine, I want to convert the following to a cleaner Update that just calls a coroutine. How would I do that? using UnityEngine public class Controller MonoBehaviour public float speed 5f private float deltaX void Start() deltaX transform.localEulerAngles.x void Update() deltaX Input.GetAxis("Vertical") speed deltaX Mathf.Clamp(deltaX, 90f, 90f) transform.localEulerAngles new Vector3(deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z)


Use an image as mask only where pixels are opaque We are into a game where to build our tile map, we carve on an image with a mask (At first the whole map is an image, and we create holes on it with tiles to create the map and le the background show. It is like substracting instead of adding new tiles in any common tiled based game). We have done this with just a tile that acts as a mask using stencil buffer. The problem comes when we want to mask with tiles where all their pixels are not opaque, for example a slope. The problem is that it applies the mask as if all the pixels in tile where opaque and we want to apply the mask in two differnet ways 1) Keep the pixels of the big image where the mask pixels are opaque 2) Mask the pixels of the big image where the mask pixels are transparent (alpha 0) I have read a lot of info about using stencil and alpha blending but can't make it work. Checking the pipeline order it seems that stencil is applied after the fragment color has been calculated. Is it possible to access the alpha value at stencil stage and write to the stencil as needed to just mask part of the image (tile in my case). Update to add a visual example


Remove previous scenes from memory in Unity 3d I'm making a game in unity3d which I optimized as much as I can. I've made different levels in each scene. After a few scenes the game starts to lag on mobile devices. And works smoothly if application is restarted and game is continued from last scene . How can I clear previously loaded scene in Unity3d or overcome the problem I mentioned above ?


How can I get sensor data on iPhone onto a Windows PC? For use as a steering wheel I am making a Unity game. I want to be able to allow the phone to be used as a steering wheel, as input into the PC game. Technically, How can I achieve this? Can this be done through bluetooth? Thanks


Unity Android game all squashed in center of screen (portrait layout), help I'm developing a demo for Android game in Unity with portrait layout. I used the ViewportHandler script found here (How do you handle aspect ratio differences with Unity 2D?) and it worked well. Yesterday I updated Unity (foolish move I know, two days before deliver of a project!!) to 5.4.2f2 (was using 5.4.1f1). I don't know if that is the reason but now I can in no way get my correct layout again. Sure, it is portrait but all squashed in the center and taking about one third of the screen, rest just background camera colour. Things looked well yesterday but now I'm in big trouble ( Any help would be greatly appreciated!


Copy location rotation information in Unity I place a cube in my level (scaled along one axis) and start doing something else. Then I place another cube, but want to copy and paste the location and rotation data from the first cube onto this new one. So far I'm doing that by copying amp pasting 6 numbers one by one. Is there a faster way to clone the location rotation of an object (eg. with a single key press)?


Multiple Scripts versus single script I have (methink) a simple question regarding attaching scripts to a GameObject. Is there any performance loss if I attach a script to a GameObject for each action to be performed (such as movement, attaking, interacting) instead of attaching a single script dealing with every single aspect? I'd like to separete these things due to clearity reasons but I wonder if calling different FixedUpdate() functions would imply some kind of issue. For example is their execution ensured to be called sequentially or they could run asincronously?


Unity How do I only show parts of objects that overlap 2D I'm working on a 2D Unity project where the player can only see objects in their field of view. I have successfully created a mesh that overlaps anything that would be in the player's field of view, but now I'm having trouble with only showing parts of objects that the mesh overlaps with. Here is what I have so far (the gray area is the player's field of view which is a mesh Here is the type of thing that I'm looking for What can I do to get that desired effect? Shaders (I have no clue how to use shaders)? Colliders? Any ideas would be greatly appreciated. If there is any info you need that I didn't provide, comment and I add the necessary info. Thank you in advance!


HDRP project error unity i just created a new HDRP project and my scene is blank. Pls Help!!! Unity view Error RenderTexture.Create failed format unsupported for random writes RGBA16 SFloat


Find asset labels at runtime Unity allows me to add multiple labels to my assets in the editor (the little blue luggage tag in the corner of the inspector). I can use the Asset Database to find all assets with a certain tag from the editor, but can I do the same thing at runtime? Maybe if the assets are in the resources folder?


RTS game unit structure I want a way to make a lot of different units without having to program stuff like moveTo and Attack actions more than once The way I see it, there are 2 ways I can do this. A single generic Unit class with flags that specifies what it can can't do (then create instances in a static array and grab them when needed) Abstract unit class with abstract methods for Unit specific actions like (Attack, Harvest, Patrol), which then all need to be implemented in the subclasses, even if the unit can't actually harvest anything. the first way of doing this seems the simplest, but i would end up having a lot of code being unused for the majority of the units. the second way could also work. But if i decide to have two different units that can harvest resources, i'm gonna have the exact same code in two different classes, which doesn't seem like the right way to do it. Is this even the right approach to this problem? In a game like AoE, every unit has, what i presume is, some kind of List of Actions Orders, I would really like to know how to achieve something similar to that, where i can just code each Action Order once, and then give it to all the units that need said Action. If i'm unclear (highly plausible) or you need more information on what exactly i'm looking for, just ask me in a comment.


Unity Inaccurate rotation if object is rotated on two axis at once I have an object which i want to rotate relative to world space. I have three variables (one for every axis) which store the rotation. By pressing buttons on my controller I add or subtract 90 to these variables (rotX, rotY, rotZ). Then I rotate my Object like this transform.Rotate (rotX delta, rotY delta, rotZ delta, Space.World) As this is called every frame the object would spin forever so i subtract the ammount I've allready rotated afterwards rotX rotX delta rotY rotY delta rotZ rotZ delta This works fine as long as I don't rotate two axis at once. Then the object rotates rotates only partially to the desired position (e.g. 83 if I want to rotate to 90). I can't see what I've done wrong. It actually seems like the moment I start an rotation around an axis all other axis get canceled. But if I monitor the variables they look exactly as they should. Thank you in advance and have a amazing day!


2D Sprites vs UI Image Scripts in Unity I am doing a 2D casual puzzle where the user can drag and drop some pieces into a board. The pieces are 2 or 3 or 4 tiles. Each tile may have text over the sprite. Target platform Mobiles and tablets. I wonder if the right approach is to use 2D sprites or to use UI images for displaying the board, the tiles and the pieces on it. On one side, doing all the game based on UI elements seem weird. On the other side, if I do it based on sprites, how do I attach texts on the sprite? Which approach should I pick?


How can I generate roads such as those in the game Twisty Road? Here is a link to see the gameplay https www.youtube.com watch?v 03PzsgO uAM How could I procedurally generate the path upon which the ball rolls in Unity C ? I know I could model distinct pieces of the road in Blender and import them into Unity as prefabs. My problem is, I genuinely have no idea where to start when it comes to programmatically generating the whole road out of those prefab sections in a cohesive manner, such that the road is built seamlessly and randomly with twists and turns in three dimensional space. I would appreciate any insight you could provide. Thank you.


Enable Disable an image inside an if statement Basically i have a code that changes the skybox after killing x amount of enemies, and i want to enable and disable four pictures inside the two if statements. I tried making three public images, set them to false and then enable them inside the every if statement but i'm pretty sure that's not how it works. I'm a noob. Here's the code public class enemyCount MonoBehaviour public static int enemiesCount 15 public Material mat1 public Material mat2 public Material mat3 void Start () void Update () print("Enemy Count is " enemiesCount) if(enemiesCount lt 10) Debug.Log("Level 2!!!") RenderSettings.skybox mat2 Heres should display image number 1 if (enemiesCount lt 5) Debug.Log ("Level 3!!!") RenderSettings.skybox mat3 Here should display image number 2 if (enemiesCount lt 0) Debug.Log ("YOU WON")


How to write a PBR Unlit Shader in Unity? I have a REALLY specific case here I have an Texture (a webcam), that is used by a shader to pickup a few x,y colors at the cordinates, and renders to a Custom Render Texture, that is later fetched (download pixel color information from GPU to CPU), and I can handle the algorithm from there. The thing is, once I upgraded the project to PBR (Physically Based Rendering), all my Unlit scripts become PINK, and they stopped working. This is a special case because It doesn't need to appear on the screen It acts as a "Compute Shader", but with backward compatibility to old phones It works well without PBR, but once PBR is enabled it becomes pink and stops working It doesn't need to reflect, refract, output pixels or anything to the "Screen", only to my Custom Render Texture so that I can fetch it later. The algorithm doesn't fits on a Graph based programming (it has iterations and etc) Well, I didn't find documentation on how to write custom PBR shaders and here I am.


How do I use virtual joysticks in Unity2d ()top view? I want to use virtual joysticks for character movement, in a top down 2D game, that includes rotating the character. I tried an Easy Joystick Unity Package, but it doesn't work properly, so what do I do? Does anyone have a script (preferably in C ) that would use virtual joysticks to move a character?


Get relative angle to collision Unity I want to get the angle between the rotation (euler Angles) of the camera (V1 Vector3) and the collision point of my character, when it hits a wall, to determin, if it was left, right, or in front of it.I tried to use Vector2.Angle with V1 and V2 (ControllerColliderHit.moveDirection as a Vector2) to get the difference between them. However I get a different value (0, 90, 180) when running into the wall depending on the world direction. (left wall, right wall, etc.) How can I get the angle of the collision point relative to the direction the camera is facing?


Why does rb.velocity blurrs background? My player controller code is bellow. So is my player inspector. This makes my character move yet it blurs the background, but when I use transform.position.x transform.right speed Time.DeltaTime it moves without blurring the background. However I'd prefer moving the character using the physics system, to avoid complications with collisions, etc.. What is going on? SerializeField public float speed SerializeField public float jumpForce private Rigidbody2D rb private CharacterAnimationsAn animationScript void Start() rb GetComponent lt Rigidbody2D gt () animationScript GetComponent lt CharacterAnimationsAn gt () gameObject.transform.eulerAngles new Vector3(0, 180, 0) Update is called once per frame void FixedUpdate() rb.velocity new Vector2(speed, rb.velocity.y) animationScript.SetRunning(true) Maybe it might be related to the Script that make the Camera follow the Player? myDistanceToFllowerDifference gameObject.transform.position objectTofollow.transform.position gameObject.transform.position new Vector3(objectTofollow.transform.position.x myDistanceToFllowerDifference.x, gameObject.transform.position.y, gameObject.transform.position.z) I have no processing stack, my camera inspector is bellow I also have a parralax script working on the background which has an inner working almost identical to this Parallax Video I should correct that it might not be a blur but actually an effect similar to a low frame rate on the background, while the player and everything show no such effect. Unfortunately I can't actually provide you with an image of the effect, as I'm not authorized to do so.


calculate force betwen two objects like angry birds game I'm trying to make a game like angry birds. in the game materials break and destroy based on force they receive. really what is the right or best way to implement it in unity? thank you for helping.


How do you de serialize a monobehaviour class? It seems JsonUtility.FromJson does not work for MonoBehaviour classes (and I can't get Newtonsoft to parse strings to Vector3s) Suppose you have a MonoBehaviour class like this (so that the values can be easily specified in inspector in editor) public class PropertyClass MonoBehaviour public Vector3 location public string name Suppose you have json data downloaded as a string called text, that you try to convert to PropertyClass format via using an JSONHelper around JSONUtility.FromJson(text) How do you have it autopopulate? If you specify a FromJsonOverwrite solution how do you have that work with JSONHelper? using System using UnityEngine using System.Collections public static class JSONHelper public static T FromJson lt T gt (string json) Wrapper lt T gt wrapper UnityEngine.JsonUtility.FromJson lt Wrapper lt T gt gt (json) return wrapper.Items public static string ToJson lt T gt (T array) Wrapper lt T gt wrapper new Wrapper lt T gt () wrapper.Items array return UnityEngine.JsonUtility.ToJson(wrapper) Serializable private class Wrapper lt T gt public T Items


Working with websockets in Unity Cannot convert lambda expression to type 'IObserver' because it is not a delegate type I'm a bit stuck on a delegate error in Unity. The code works fine if I'm in a c console app however Unity is giving me the error Cannot convert lambda expression to type 'IObserver' because it is not a delegate type. client.ReconnectionHappened.Subscribe(type gt Log.Information( quot Reconnection happened, type type , url client.Url quot ) ) I tried updating to the latest Unity for the c 8 support but that didn't appear to fix anything. I'm guessing it has something to do with .net compatibility and Unity. Do I need to create this delegate some other way to be compatible with unity? I've been looking at the code here. Websockets Server for Unity3d Using this for the client https github.com Marfusios websocket client


Instantiate unity sometimes lags the game some times it doesnt I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems. Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation. Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case. See here a screenshot for object A, and its components See here object B and its components Per request the code that does the instantiation of the objects public class ForLoopVisualization1 MonoBehaviour public DetectorAreaScript ElementDetector public GameObject TowerElement public Transform TowerElementsParent public bool WigglyTower false public float ElementSpacing, Wiggeliness private Collider BuildElementCollider private Transform BuildElementTransform private Vector3 TowerElementPos private int TowerElementCount, CreatedElements private bool StartBuildingTower false private float Delay 0.5f, TowerElementSize Use this for initialization void Start () ElementDetector.DetectedData OnObjectEnterDetector Destroy(TowerElement.GetComponent lt Rigidbody gt ()) TowerElementSize TowerElement.GetComponent lt Collider gt ().bounds.size.y TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) Update is called once per frame void Update () if(StartBuildingTower amp amp CreatedElements lt TowerElementCount) Delay Time.deltaTime if(Delay lt 0) CreatedElements var te Instantiate(TowerElement, TowerElementPos, Quaternion.identity) te.transform.SetParent(TowerElementsParent) if(WigglyTower) TowerElementPos new Vector3(Random.Range( Wiggeliness, Wiggeliness), TowerElementSize ElementSpacing, Random.Range( Wiggeliness, Wiggeliness)) else TowerElementPos new Vector3(0, TowerElementSize ElementSpacing, 0) Delay 0.4f else if(StartBuildingTower) StartBuildingTower false StartCoroutine(EjectVar()) add when bugs are fixed.. void OnObjectEnterDetector(System.Object sender, DetectedVariableData data) if(data.DetectedObjectType DetectedType.Variable) var vals ElementDetector.DetectedVariable.GetVariableValue() TowerElementCount vals.IntValue if(CreatedElements gt 0) foreach (Transform child in TowerElementsParent) Destroy(child.gameObject) CreatedElements 0 TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) StartBuildingTower true IEnumerator EjectVar() yield return new WaitForSeconds(0.8f) ElementDetector.EjectDetectedElement(new Vector3( 1, 0, 1)) If something is unclear let me know so i can clarify the post!


How to create "broken glass" animation? I have started making a 3D game in Unity5 that consists in avoiding obstacles. It is very easy but I want to add a collision effect when I collide on the wall. I would like to slice the screen into many parts (random pieces is better) that are falling down from screen with gravity. An example of what I mean How can I do this? I've tried using a lot of different images (shapes) but I'm sure that is not the best way... Thanks for any suggestions.


Unity3D How to just center a mesh inside a character controller! Hi I have a simple character mesh and it's parented to my character controller invisible capsule object and all the moving code is applied to the parent (if that's relevant), but the point Is I'm trying to line up the mesh to be exactly inside the capsule to make it look like the player is walking ABOVE the ground (pretty normal ...?) So by default the character controller is origined in the center so I move it up by half of it's height to try to get it to line up with the character mesh, which has it's origin below it's feet a little, and this is the result as you can clearly see, his feet slightly go into the ground, I have no idea why this is happen, then should be just above the ground like any other normal feet! Here's the code for setting the capsule up half of it's width, since it starts by lining up the mesh in it's CENTER for some reason Vector3 tempPos player.transform.position tempPos.y (capsuleSize.y 2) chassidSize.y 12 chassid.transform.position player.transform.position player.transform.localPosition tempPos chassid.transform.parent player.transform and here's a picture of the mesh (which is just a blender file, easier for import) As you can see, in the blender file, the origin is slightly below the characters feet, IN THE CENTER, so I don't know why it's not working as planned. Also, you can see in the first picture that he's slightly moved to the center of the controller on the z(?) axis, but I want him to be completely centered in, any idea how to fix this?


Unity highlight outline mesh edges border (make them visible) Let's say I create a cube using mesh triangles similar to the graph below. I would like to make those 12 edges visible in play mode so user player can see them too (but without the diagonals). What would be the best way to approach this problem in unity? Hundreds of cubes will be created in run time using mesh triangles and the vertices position (vector3 value) will change at some point, so I am wondering if there's a way that allows those edges to change move along when the mesh triangles change and the edges still remain visible the whole time. The desired outcome should be similar to the shaded wireframe in the scene view. Any help would be appreciated.


How can I limit the rotation angle of the object? At the top float speed 1.0f float rotationAngle 45 In Update private void Update() if (Mathf.Approximately(transform.localPosition.y, 7)) float rotationY rotationAngle Mathf.Sin(Time.time speedRot) transform.Rotate(new Vector3(0f, rotationY, 0)) but it's just rotating nonstop at the same direction. I need it to rotate for example in the limited range of 45 to both sides like a ping pong from side to side. and optional to make it to rotate in limited angle s for all axis but now for the Y how to limit it like a ping pong to rotate 45 degrees to the right then back to the left and so on nonstop but in limited angle s.


Objects rendering only on editor, but not on build (they get invisible) Everything works fine in the editor, but when I build the game, none of the objects in the scene are rendered, and only the skybox and UI text is visible. But although they aren't appearing, they are working as normally (i.e. these objects' triggers work normally when the determined event occurs, like for example, colliding to a specified object, or in other words, they are invisible). I searched for this issue but didn't found any answer. Could it be my cheap computer's fault (Intel Celeron without an external graphics card)? In editor game mode In buit game I ran both the editor and the built game in the same quality, and also tried to run it in Fastest quality, but no, it made no difference in the built game. Also, there is no object tagged with "Editor only", only one have a custom tag and all the others are "Untagged". And the camera's culling mask is set to "Everything". The result is the same either for web or Windows. Edit OK, I built for Android and the objects render normally. So, I'm not completely sure, but probably it's my PC that can't render the objects, because both building for web plugin and desktop have this disappointing result, but for Android it works perfectly (even the shadows, which wasn't being cast in the editor), so...


Why do my .wav sound effects delay before playing the first time on iOS? First off, I'm using Unity 5.2.3. I have a bunch of .wav sounds that I play like this Debug.Log(m audioAssets.m soundBanks (int)m currentSoundBank .m multiplier data .loadState) m multiplierSource.clip m audioAssets.m soundBanks (int)m currentSoundBank .m multiplier data m multiplierSource.Play() The Debug.Log is just there temporarily, to verify that the sounds' loadState is "loaded". It is, every time they play. But the first time they play on my iPhone, there is a noticable delay before they start. After playing the first time, they work fine. What am I supposed to do to get these sounds to preload properly? I have their "Preload Audio Data" boxes checked in the import settings, and they're set to "Decompress on Load".


Distributed Rendering in the UDK and Unity At the moment I'm looking at getting a game engine to run in a CAVE environment. So far, during my research I've seen a lot of people being able to get both Unity and the Unreal engine up and running in a CAVE (someone did get CryEngine to work in one, but there is little research data about it). As of yet, I have not cemented my final choice of engine for use in the next stage of my project. I've experience in both, so the learning curve will be gentle on both. And both of the engines offer stereoscopic rendering, either already inbuilt with ReadD (Unreal) or by doing it yourself (Unity). Both can also make use of other input devices as well, such as the kinect or other devices. So again, both engines are still on the table. For the last bit of my preliminary research, I was advised to see if either, or both engines could do distributed rendering. I was advised this, as the final game we make could go into a variety of differently sized CAVEs. The one I have access to is roughly 2.4m x 3m cubed, and have been duly informed that this one is a "baby" compared to others. So, finally onto my question Can either the Unreal Engine, or Unity Engine make it possible for developers to allow distributed rendering? Either through in built devices, or by creating my own plugin script?


How Many Entities can the Unity Game Engine Handle Before it Starts to Lag? I am building a player model for my game, the model is very complicated due to its ability to be customizable. A single player entity can have 70 entities including the head, parts to the face, arms, legs, shoes, and the clothes and armor it wears, and the weapons it has equipped. I just need to know, at what point does the unity game engine start lagging due to too many entities? Also, the game is low poly, there are many entities, but each one is block based, or very simple in design.


Level Selector with possible future levels? Unity I have a level select screen which is a simple grid layout of my levels. The level data comes from a scriptable object for each level. The problem I have is what is the best method for populating the grid of levels that use the scriptable object and is able to add more levels to the grid layout if let's say I add an asset bundle in the future? My thought was that I use a levelDB which holds a list of all of the scriptable objects. Then when an asset bundle is used then it adds the content to the levelDB. The UI would then just use this levelDB to populate the screen. NOTE I have very little to no knowledge of how asset bundles work and what you can, and cannot do with them.


Unity Camera Follow target with view port point's offset from center Some additional remarks before I address the issue How Viewports work in Unity Whatever the dimensions of the screen's rect, the viewports coordinates are mapped in normalized coordinates, where 0 represents left and bottom, for x and y respectively, and 1 right and top, for x and y respectively (image below). Follow a Target (Easy implementation for the sake of demonstration) Consider this following simple algorithm to follow a target CameraFollowExample MonoBehaviour public Transform target public bool relativeToTarget public Vector3 followOffset private void LateUpdate() if(target ! null) FollowTarget() private void FollowTarget() transform.position target.position (relativeToTarget ? target.TransformDirection(followOffset) followOffset) transform.Lookat(target) Issue The following works as expected, but the target will always be at the viewport's center ( 0.0, 0.0 ) What I am trying to Achieve This is what I am trying to achieve make camera follow a given target, with an additional offset from the viewport's center. This offset being additional to the following offset applied to the target. So for example, if I define two ranged floats, centerX and centerY respectively, I'd like the camera to be positioned with an additional offset, so the defined offset is at the target. As an example, on the image below, I have centerX and centerY on 0.2, 0.25 respectively, so the target should be at that viewport's point. Having a resulting (partial) script CameraFollowExample MonoBehaviour public Transform target public bool relativeToTarget public Vector3 followOffset Range(0.0f, 1.0f) public float centerX Range(0.0f, 1.0f) public float centerY private void LateUpdate() if(target ! null) FollowTarget() private void FollowTarget() Vector3 destination target.position (relativeToTarget ? target.TransformDirection(followOffset) followOffset) transform.position destination GetCalculatedOffset() transform.Lookat(target) private Vector3 GetCalculatedOffset() interpret the Vector centerX, centerY to return an offset. return (interpretedOffset target.position) What I have already tried Make the camera position to the destination plus an offset of the center centerX, centerY 0.5, 0.5 , the direction is ok, but obviously, the target is not positioned at the expected viewports' point coordinate. Have a global vector that is the custom center point relative to the camera's transform and the nearPlane, and then make an offset between that point and the target, ignoring the z. The camera gets away from the target. What I am not trying to achieve Something like following example (define an additional offset vector, and position the camera with the additional offset) CameraFollowExample MonoBehaviour public Transform target public bool relativeToTarget public Vector3 followOffset public Vector3 additionalOffset private void LateUpdate() if(target ! null) FollowTarget() private void FollowTarget() Vector3 destination target.position (relativeToTarget ? target.TransformDirection(followOffset) followOffset) transform.position destination additionalOffset transform.Lookat(target) I mean, this technically works, since the target won't be at the center of the viewport. But the intention is for the target to be positioned at the defined viewport's point. Any additional information you may need, let me know. Thank you beforehand, and Happy New Year.


Make movement speed relative to player character rotation in Unity? I'm doing a strict topdown 2D game where the character looks at wherever the mouse is pointing (same perspective as GTA 2 or Darkwood) . I want to make movement speed for strafing and backing up slower than walking forward. I'm having a hard time figuring out how to do this using Angle() and understanding vector math. Any help would be appreciated


3 hit combo system plays first attack animation every time So the new input system is out, and we're using it for our game. The next hurdle I'm trying to get over is implementing a melee combo ( E E E). Not 100 sure how to get the new system to execute something like that. Right now my trigger isn't resetting. Images of the animator graph at the bottom public class PlayerController MonoBehaviour Rigidbody2D rigidbody SpriteRenderer renderer Animator animator public float fallMultiplier 2.5f public float lowJumpMultiplier 2f PlayerInputActions inputActions Vector2 movementInput public bool inInteractionZone public int attackCount 0 public float attackTimeout 0.5f bool touchingWall private void Awake() HRHEventHub.OnPlayerDeath HRHEventHub OnPlayerDeath inputActions new PlayerInputActions() inputActions.Player.Move.performed ctx gt movementInput ctx.ReadValue lt Vector2 gt () inputActions.Player.Interact.performed InteractPressed private void InteractPressed(InputAction.CallbackContext obj) TODO add attack timeout Check if we are inside a interaction zone if (inInteractionZone) TODO implement return if (attackCount 0 amp amp grounded) attackCount animator.SetTrigger("Attack") animator.SetBool("ATK1", true) else if (attackCount 1 amp amp grounded) attackCount animator.ResetTrigger("Attack") animator.SetTrigger("Attack") else if (attackCount 2 amp amp grounded) attackCount 0 animator.ResetTrigger("Attack") animator.SetTrigger("Attack")


Create a 2D trail in Unity? I would like to make a trail for a pixelated snake such as this one As you can see, the cross simply repeats itself to create the snake. In Unity I have messed around with Trail Renderer, tried everything to import the cross as a texture sprite, then created all sorts of materials for it, but it just won't work the same way. How can I achieve this effect please? Thanks!


How does Against The Wall create an infinite wall? There is a game called Against The Wall, developed by Michael P. Consoli. It's a fantastic game, as I've always been stumped at how the game creates an infinitely spanning wall. In the game, you can fall forever, and the wall will keep spanning. I can fall as long as I like, and still be able to climb back to where I was before. The game is developed in Unity. How can a game do this without crashing, or creating some kind of memory overload?


Display hide image with zoom in out After spending a while looking through the forums, I haven't been able to find a thread that deals with transforms on an image. Essentially, what I'm trying to do is display and hide an image at the start of a level in a game I'm working on. The image should start out large and with 100 transparency, then shrink to a certain size within the camera bounds with no transparency, idle for a second, then fade back out the way it came. How would this be done programmatically? Thanks in advance!


How do I change the game object on a button click? I have a five game objects (ornament1, ornament2, ornament3, ornament4 and ornament5) and two buttons ("Next" and "Previous"). When I click "Next", the object should change from ornament1 to ornament2. When I click "Next", again, it should change from ornament2to ornament3 when I then click "Previous" it should change from ornament3to ornament2. I have the "Next" button working, but the "Previous" button is not working. How do I change the game object on a button click? Here is my code if(GUI.Button(new Rect(10, 20, 80, 50), "Ornament1")) Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh" countbool) if(count 0) Debug.Log("hhhhhhhhhhhhhhhhhhhhhhh") ornament1.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament1.SetActive(true) ornament2.SetActive(false) ornament3.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 1) ornament2.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament2.SetActive(true) ornament1.SetActive(false) ornament3.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 2) ornament3.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament3.SetActive(true) ornament1.SetActive(false) ornament2.SetActive(false) ornament4.SetActive(false) ornament5.SetActive(false) count else if(count 3) ornament4.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament4.SetActive(true) ornament3.SetActive(false) ornament1.SetActive(false) ornament2.SetActive(false) ornament5.SetActive(false) count else if(count 4) ornament1.SetActive(true) ornament5.transform.position new Vector3( 0.1428955f, 0.1894745f, 4.108555f) ornament5.SetActive(true) ornament3.SetActive(false) ornament1.SetActive(false) ornament2.SetActive(false) ornament4.SetActive(false) count


change the pivot point of an empty object I have couple of objects and put them inside the empty object (to act as custom pivot point) . Now, i want to change the pivot of the empty. Normally i will unlink the objects first, move the empty to desired position and then link the object back (as child). But is it possible to change the pivot of the empty without unlink the objects first ?


How can I run a Unity game in a window larger than the desktop resolution? I am exploring a research problem using Unity. I require a game resolution of at least 4096 x 786. There seems to be no option under build settings for setting a fixed screen size window. (The default screen width and height options are unhelpful here.) How can I make a window even larger than the desktop?


Unity 5 Error with code to make pitch changes based on distance I really need help. It's 2 00 AM here and my brain is half dead so I can't, for the life of me, find out what's wrong with this code anymore. It's supposed to find the distance between the game object to which it's attached (the target), and another game object (the player). Then, depending on the that distance, it should change the pitch of an AudioSource inside a child (in the player). However, the pitch only changes when I'm practically over the gameobject. So, for about 9 10 of the way, nothing changes in the pitch, but when I'm right there the pitch suddenly changes (but not to maximum value of Clamp function). What's going on? I want the pitch to, at first, stay at 0. But soon after you walk some steps in the right direction, the pitch must change gradually (and in a evenly manner), as (player) gets closer to (target). ps. The script is inside a instantiated prefab, that's why I used FindGameObjectWithTag and FindChild. Also, I'm using Unity 5. lt ! language lang cs gt four blanks using System.Windows.Controls more indented code using UnityEngine using System.Collections public class ProximitySensor MonoBehaviour public GameObject player private Transform playerTrans private Transform targetTrans public Transform beepTrans public AudioSource beepSound private float distanceCurrent void Start () targetTrans transform player GameObject.FindGameObjectWithTag("Player") playerTrans player.transform beepTrans playerTrans.FindChild ("beepController") beepSound beepTrans.GetComponent lt AudioSource gt () void Update () distanceCurrent Vector3.Distance (playerTrans.position, targetTrans.position) beepSound.pitch Mathf.Clamp ((1 distanceCurrent), 0.1f, 3.0f)


How can I limit the y rotation of a cinemachine POV camera based on the player's direction? I'm using Unity (2019.4.11.f1, HDRP). My goal is to create a first person POV camera. To this purpose, I tied a Cinemachine (2.7.3) Virtual Camera to the head of a third person player character (one from the Basic Locomotion demo of this asset). The Body of the camera is set to 'Hard Lock to Target', Aim to 'POV', and Recenter Target to 'Follow Target Forward'. This works fine. The camera has a Horizontal Axis Value Range ( to ), that limits the rotation of the camera, but I cannot figure out how to tie this to the rotation of the Follow component (the head of the avatar). When I walk my character around, the camera can only rotate within the set Value Range angle that has it's 0 point in one absolute direction (let's say north), independent of the player's orientation. It seems to use World Orientation, but I don't know and wasn't able to find out where to change that. Does anyone know how I can change this behaviour?


Trying to create a '2D 8 Ball Pool' game Trajectory Prediction I am trying to create a game similar to (Pocket Run Pool) https www.youtube.com watch?v ewlAE6NQnsI amp t 215s a 2D pool game that is much simpler than a 3D one I need help with creating code for trajectory prediction something similar to this https docs.unity3d.com Manual physics multi scene.html How do I go about doing this?


How to avoid many import iterations while generating sub assets? I have a ScriptedImporter that generates other assets in the same directory. Whenever it happens, import progress bar pops in again, this time like Importing (iteration N). I've tried to use AssetDatabase.DisallowAutoRefresh to circumvent this behavior but that failed. Question How to prevent subsequent import iterations and rather group them to happen all at once ?


Unity raycasting not always detecting component I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work In update I call if (Input.GetMouseButtonDown(0)) selectedObject null selectedUnits new List lt Unit gt () Select(Input.mousePosition) startPos Input.mousePosition which calls void Select(Vector2 screenPos) Ray ray cam.ScreenPointToRay(screenPos) RaycastHit hit Debug.Log( quot 1 quot ) if (Physics.Raycast(ray, out hit, 100)) OnClicked(hit.transform.tag) Debug.Log( quot 2 quot ) if (hit.transform.GetComponent lt Unit gt ()) Debug.Log( quot 3 quot ) if (!selectedUnits.Contains(hit.transform.GetComponent lt Unit gt ())) Debug.Log( quot 4 quot ) selectedUnits.Add(hit.transform.GetComponent lt Unit gt ()) if (hit.transform.GetComponent lt Building gt ()) if (hit.transform.GetComponent lt Building gt () ! selectedObject) selectedObject hit.transform.gameObject Detecting a quot building quot always works and is fine, but clicking on a quot unit quot works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not). This is the Unit in the inspector and this is it in the hierarchy When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time. it seems like after each hit the ray penetrates the collider more and more But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider. I hope someone knows what's going wrong, thanks!


How to express and verify euler rotation limits in Unity I need to find a way to set min and max angles for each Euler component and check whether transform.localEulerAngles falls within those limits. My current code looks like this class JointLimit MonoBehaviour SerializeField Range( 180f, 180f) private float minX 180f SerializeField Range( 180f, 180f) private float maxX 180f SerializeField Range( 180f, 180f) private float minY 180f SerializeField Range( 180f, 180f) private float maxY 180f SerializeField Range( 180f, 180f) private float minZ 180f SerializeField Range( 180f, 180f) private float maxZ 180f public float Error get Vector3 localEuler transform.localEulerAngles Vector3 signedLocalEuler new Vector3(Mathf.DeltaAngle(localEuler.x, 0), Mathf.DeltaAngle(localEuler.y, 0), Mathf.DeltaAngle(localEuler.z, 0)) float error 0 error Mathf.Max(0, minX signedLocalEuler.x) error Mathf.Max(0, signedLocalEuler.x maxX) error Mathf.Max(0, minY signedLocalEuler.y) error Mathf.Max(0, signedLocalEuler.y maxY) error Mathf.Max(0, minZ signedLocalEuler.z) error Mathf.Max(0, signedLocalEuler.z maxZ) return error This basically checks whether the Euler components fall within the specified range and sums the exceeding angles up to an error. The problem is that Unity internally stores rotations as Quaternions and that there can be several euler representations for a single Quaternion, like Euler 123f, 17f, 235f and Euler 57f, 197f, 55f are the same thing. Is there any way I can bring an Euler representation into some kind of normalized form that allows me to reliably check it against my limits?


Hierarchical "Select GameObject" Dialog or names with prefixes? I am attempting to connect a series of teleporters with entrances inside a single scene. Once the player touches a teleporter he is moved to another place. I am doing this by simply connecting two game objects as shown in the following screenshot. The particle system in the center of the upper side is used as teleporter, the red line indicates the game object where the player will be transported to. Sadly, this results in an utter mess when attempting to select a new entrance the teleporter should link to. There is no way to guess which entrance corresponds to which side and dice So the tl dr of my problem would be this The name of the object that should be selected is meaningless when isolated. It's the path to the object (or in other terms the name of some parent) that is relevant. I would see three possibilities to solve this, but sadly I haven't gotten around to find out how to do any of them. Switch the "Select GameObject" Dialog to use the same hierarchical view as used in the scene viewer. Is there a hidden option somewhere in Unity that I overlooked? Somehow prefix the names of my entrances programatically. Is there a way to include the path to a certain game object in its name? My whole approach is backwards and I am doing something in a not Unity friendly way. But what would be the "correct" way to do this?


Why moving platform script is not working? I have some code attached to a moving platform public Transform pos1, pos2 public float speed public Transform startPos Vector3 nextPos Start is called before the first frame update void Start() nextPos startPos.position Update is called once per frame void Update() if (transform.position pos1.position) nextPos pos2.position else if (transform.position pos2.position) nextPos pos1.position transform.position Vector3.MoveTowards(transform.position, nextPos, speed Time.deltaTime) private void OnDrawGizmos() Gizmos.DrawLine(pos1.position, pos2.position) But my platform does not go to the pos2 when it reaches the pos1. What is wrong here?


Ordering a List doesn t work. InvalidOperationException Operation is not valid due to the current state of the object I have this method. It s for ordering actors and only displaying the ones which are in direct line of sight with the player. public Actor OrderActorListByDistance(List lt Actor gt list, Vector2 pos) return list.FindAll(d gt Physics2D.Linecast(d.transform.position, pos, LayerMask.GetMask("Default")).collider null).OrderBy(i gt Vector2.Distance(pos, i.transform.position)).First() But that Method throws that error InvalidOperationException Operation is not valid due to the current state of the object I already made a lot of google research but I couldn t find any solution. I would appreciate any suggestion or help. Thanks in advance


WebGL Redirecting URL If player's browser don't support WebGL, I want to redirect Web Player version. I think it's possible in UnityLoader.js file but how? function CompatibilityCheck() hasWebGL?mobile?confirm("Please note that Unity WebGL is not currently supported on mobiles. Press Ok if you wish to continue anyway.") window.history.back() 1 browser.indexOf("Firefox") amp amp 1 browser.indexOf("Chrome") amp amp 1 browser.indexOf("Safari") amp amp (confirm("Please note that your browser is not currently supported for this Unity WebGL content. Try installing Firefox, or press Ok if you wish to continue anyway.") window.history.back()) (alert("You need a browser which supports WebGL to run this content. Try installing Firefox."),window.history.back()) I just want to add a URL redirect here.


Unity is not responding in Ubuntu 18.4 I am running the build Unity executable in ubuntu 18.04 and it may take a while to load the asset. When I wait, I always receive a window telling me "You can choose to wait for a while to let it continue or force the application to completely exit." For a while, Unity will run and it looks like works well. My question is, what is the impact of this? Why does ubuntu send the message? How to deal with it?


Character rotation according to camera causes rapid flipping when game starts When I load my scene, my character rotates 90 and 90 on the X axis very fast about 4 or 5 times, and then he stops at 90 on X axis (lays back down). When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game. Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object. void Update() Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed Vector3 deltaPosition transform.position prevPosition if (deltaPosition ! Vector3.zero) transform.forward deltaPosition prevPosition transform.position


Why won't my integer go down when my function is called? I'm trying to implement a limited use slow mo power into my game using C , but I can use it infinitely. Why won't my integer go down when my function is called? using UnityEngine public class TimeManager MonoBehaviour public float slowdownFactor 0.05f public float slowdownLength 2f public int slowmos 5 private void Update() Time.timeScale (1f slowdownLength) Time.unscaledDeltaTime Time.timeScale Mathf.Clamp(Time.timeScale, 0f, 1f) public void SlowMo() if (slowmos ! 0) Time.timeScale slowdownFactor Time.fixedDeltaTime Time.timeScale .02f slowmos using System.Collections using System.Collections.Generic using UnityEngine public class charcterMovement MonoBehaviour public TimeManager timemanager public Rigidbody rb public float forwardForce 1000f public float rightForce 100f public float leftForce 100f Start is called before the first frame update void Start() rb.useGravity true Update is called once per frame void FixedUpdate() rb.AddForce(0, 0, forwardForce Time.deltaTime, ForceMode.VelocityChange) Set Speed To Cube if (Input.GetKey( quot d quot )) rb.AddForce(rightForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot a quot )) rb.AddForce(leftForce Time.deltaTime, 0, 0, ForceMode.VelocityChange) if (Input.GetKey( quot space quot )) timemanager.SlowMo()


Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)


How to make a PROPER main menu (or any other UI windows modals) in Unity? So, I'm currently learning both about Unity for the first time as well as the 'new' 2D UI system, but I'm having a hard time figuring out how to make windows, modals dialogs, main menus etc. which are not only functioning, but also modular, reusable and written following proper coding standards. Most how to's, blogs, Q amp As or tutorials I find only cover the most basic parts of UI development (e.g. how to drag a button from the toolbar to the scene window in 2 hours). So basically, I'd like to have a main menu which meets those (very common) requirements A button which 'starts' the game (e.g. by simply loading another scene) A button which 'quits' the game, but also opens up a confirmation dialog before A button which opens up an options dialog, which again is composed of multiple parts (audio, video...) and finally, it should be possible to go back to the previous screen using a 'back key button', for example Escape What I started with is a canvas which I called GameMenu. This canvas has several nested canvases, such as MainMenu OptionsMenu OptionsMenuAudioPart OptionsMenuVideoPart CancelMenuModal Then I created a menu script which works as some sort of state machine public class MenuScript MonoBehavior private GameObject currentStateObject private GameObject previousStateObject public void SetState(GameObject newStateObject) if(newStateObject null newStateObject) return if(CurrentStateObject ! null) CurrentStateObject.SetActive(false) previousStateObject currentStateObject CurrentStateObject newStateObject CurrentStateObject.SetActive(true) Every button has now an event trigger attached which calls the SetState(...) method on MenuScript. However, I've got the following problems How do I pass multiple parameters to methods invoked by event triggers? As soon as I add another parameter to SetState(...), for example bool isModal false to tell the method that it shouldn't disable the previous state, then it disappears from the event trigger action selection menu. How to I register key press events within the event triggers? It's easy by script (Input.GetKey(...) etc.), but I didn't find one on the event type selection. How do I make e.g. event triggers conditionally? So that certain events cannot be called when certain states are active? I know I can solve all those problems within the script and make a fully functional main menu which does exactly what I want, but then... I cannot use it for something else I don't use the new Unity UI system, which makes me wonder what's the purpose of it I got to reference all involed game objects (the canvases, buttons etc.) in script, which makes it not really 'extendable' anymore as this means for every changed requirement, I have to alter the script (e.g. a new state, menu, button etc) The main goal in the end is a script which I can use for all kinds of UIs without writing the same logic over and over again just because it's another scene, game state etc.


How To Place Object On Ground Within Radius? I'm using Unity and I'm building an object placement system where you'll be able to position objects around the player. I'd like to place objects flush with the ground, parallel to world up, even on slopes, so I'll use a raycast for that. How would I limit the distance to maxDistance? I tried using ScreenPointToRay but the max distance on the raycast makes the movement of the object stop if the raycast doesn't hit. As an example, If I'm looking down in front of me, the object i'm controlling should be at that position. However, if I'm looking straight forward into Infinity, the object should only ever be maxDistance away. If I rotate, the object should follow smoothly. Thanks! edit here is a video of what I have now, but as you can see, the object gets stuck if the raycast doesn't hit anything due to the maxDistance. It doesn't get stuck if i use Infinity for the ray distance, but then the object doesn't respect max distance like I want it to. https streamable.com bacij8 Code snippet https gist.github.com zackperdue 270e9574bed4a937bef791fb41512291


gazing and lip syncing in Unity 5.2 Is it possible to achieve gazing or lip syncing in Unity 5.2 at all, similar to Locomotion done through MecAnim?


OnMouseUp not working in unity A common problem in Unity my OnMouseUpAsButton() is not being called, and I do not understand why. I have attached box collider 2d (though its size is set up during runtime, but by the time I click on it it has proper size and covers the whole button). My object is an UI element, created from prefab during runtime. Here you can see its inspector info Code using UnityEngine using System.Collections public class button controller MonoBehaviour void OnMouseUpAsButton() Debug.Log("Clicked event button") switch(click action) case action.NONE action none() break I tried going through other threads where people had similar problems but nothing seems to work. Any ideas what might be happening? EDIT I found out that if I add a new button , directly from the inspector to the canvas, whose collider is within the canvas all other buttons start working. Interestingly I cannot put this new button anywhere, it has to be at least a bit within the canvas


Programmatically generated mesh vertex colors not showing up in Unity? I'm sorry if this is an obvious thing to solve but I just can't figure it out...did I miss something...I've generated a mesh and during vertices generation I've also set its colors (and colors32 just in case) by reading those values from a ply file, and afterwards I've added a number of vertex color shaders but none of them will show the vertex point colors in play mode, it's either solid black or just like I added no material to the mesh (which I've tried doing manually in play mode too). Did I miss something please?


How can I change the rotatearound radius in real time when the game is running? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Range(0, 50) public float xradius 5 Range(0, 50) public float yradius 5 private void Start() Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Using the xradius and yradius sliders I want to change the transform.RotateAround radius in real time. UPDATE I added this to the Update if (radius gt 0) var newPos (transform.position Turret.transform.position).normalized radius newPos Turret.transform.position transform.position newPos The problem is now that some times when the radius the distance from the Turret is small for example 20 or less some times the transform is getting right above the turret not sure why. I want it to rotate around the turret at the fixed set distance(radius) but not to be above the turret. Can't figure out why sometimes it's moving right above the turret then after some time it's getting back to the set distance.


where can I download unity assets without opening it in in unity. I'm browsing through my mobile phone and I need to download unity assets but unity asset store demands that I open the assets in unity directly. How or which site can I download it on my mobile and send it to my PC.


Unity Hub 2.4.2 does not open a login window I just installed Unity Hub 2.4.2 on my MacBook Pro 2015 running macOS Big Sur. However, when attempting to open a login window from the hub, it opens briefly and then quits. (The hub remains open, but the login window closes.) I've already tried Quitting and reopening the hub Uninstalling and reinstalling the hub Are there any suggestions on how to fix this? Does anybody have the same problem?


Save Script Doesn't Save Item Variables I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System using System.Collections using System.Collections.Generic using UnityEngine using System using System.Runtime.Serialization.Formatters.Binary using System.IO public class InventorySave MonoBehaviour Public variables for inventory and health private GameObject itemHolder private ItemInformation myItemAmount Initiates before the first frame void Start() Gets components for the player variables itemHolder transform.gameObject myItemAmount itemHolder.GetComponent lt ItemInformation gt () Function that will be called when player saves game from pause menu public void SaveGame() Creates file to store variables BinaryFormatter bf new BinaryFormatter() FileStream file File.Create(Application.persistentDataPath quot SaveData.dat quot ) SaveData data new SaveData() Gets the player data data.itemSave myItemAmount.itemAmount Writes player data to file and encrypts it bf.Serialize(file, data) file.Close() Holds data that is to be saved Serializable class SaveData Variables for save file public int itemSave


Why do prefabs speed up loading? I have a scene with a massive terrain. It took a long time to load (approximately 60 seconds) when I pressed play. I am in the editor. I prefabbed it. Now it only took about 5 seconds to load when I pressed play. Why? My best guess is that there is some preloading done when it is prefabbed, but it only takes a few seconds to prefab it. So that couldn't be the reason. Any ideas? I am at a loss.


How can I add a batch of sprites to a list in Unity's inspector? I have a C script with a public property List lt Sprite gt someSprites I would like to add 20 sprites to it, from the inspector window. However, it seems like the only way to do so is to drag one by one. Is there a simpler way to batch fill lists in Unity?


How can I get Unity to do letterbox pillarbox to maintain aspect ratio? I'd like my game to have the same aspect ratio at all cost, including keeping all UI elements fixed in the same place. I'm totally ok with losing screen space in the interest of fixing the aspect ratio.


How to animate an arc from the middle in both directions I have been able to make an arc that animates from one end to another using the following coroutine IEnumerator AnimateArc(float duration) float waitDur duration pts for (int i 0 i lt pts i ) float x center.x radius Mathf.Cos(ang Mathf.Deg2Rad) float y center.y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLineRend.positionCount i 1 arcLineRend.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts yield return new WaitForSeconds(waitDur) How can I animate this arc from the middle in both directions at a constant speed with an ease (animates slightly faster in the middle and slows down towards the end)


Most optimal way to find closest object So currently ive been using the physics.castSphere method with a small radius to find the closest of an object with a tag. However this is pretty performance heavy so my question is, is there a way to optimize it? i have also been looking at keeping a list of gameobjects and just looping through those however doing that a few times a frame for each object searching also seems rather performance intensive. Here is my case 50 individual characters on team 1 50 individual characters on team 2 each character has to find the closest of the character from the other team. What is the fastest and least performance heavy way of doing it?


Unity shader set to GameObject position I have a shader with acts like a magnifying glass that I downloaded and I have to attach to the camera scene. My issue with this I want it in the same fixed position as the sprite but being attached to the camera when I changed the screen size for different devices it wonders to the upper right of the screen. I am completely new to shaders so I and their scripts so I am not sure if this can be done. private void OnRenderImage(RenderTexture src, RenderTexture dest) if (mtrl null mtrl.shader null !mtrl.shader.isSupported) enabled false return if(Input.GetMouseButton(0) !detectMouseButtonDown) mtrl.SetFloat(" Radius", radius) mtrl.SetVector(" Mouse", new Vector4(740, 480, 0)) mtrl.SetFloat(" Distortion", distortion) mtrl.SetFloat(" ScaleArea", scaleArea) if(isMagnifyingGlass) mtrl.EnableKeyword("IS MAGNIFYING GLASS") else mtrl.DisableKeyword("IS MAGNIFYING GLASS") if(warpType WarpType.POW) mtrl.EnableKeyword("WARP TYPE POW") mtrl.DisableKeyword("WARP TYPE EXP2") else mtrl.DisableKeyword("WARP TYPE POW") mtrl.EnableKeyword("WARP TYPE EXP2") Graphics.Blit(src, dest, mtrl, 0) else Graphics.Blit(src, dest) Shader Shader "Hidden MagnifyingGlassFisheyeWarpImageEffect" Properties MainTex ("Texture", 2D) "white" SubShader Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma target 3.0 pragma multi compile WARP TYPE POW WARP TYPE EXP2 pragma multi compile IS MAGNIFYING GLASS include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float4 pos SV POSITION float4 scrPos TEXCOORD0 float2 uv TEXCOORD1 sampler2D MainTex float4 MainTex TexelSize float2 Mouse float Radius float Distortion float ScaleArea v2f vert (appdata v) v2f o o.pos UnityObjectToClipPos(v.vertex) o.scrPos ComputeScreenPos(o.pos) o.uv v.uv return o fixed4 frag(v2f i) SV Target float4 c 0 float2 uv i.scrPos.xy i.scrPos.w float2 mousePos Mouse.xy ScreenParams.xy float wh ScreenParams.y ScreenParams.x uv.y wh mousePos.y wh if(length(uv mousePos) lt Radius) uv mousePos if defined(IS MAGNIFYING GLASS) float newLength ScaleArea Distortion ScaleArea pow(length(uv) Radius, Distortion) else if defined(WARP TYPE POW) float newLength ScaleArea pow(length(uv) Radius, Distortion) endif if defined(WARP TYPE EXP2) float newLength ScaleArea exp2(length(uv) Radius Distortion) endif endif uv newLength uv mousePos uv.y wh c tex2D( MainTex, uv) return c ENDCG Here is what it looks like over the gold selector. It is in the correct position. Now if I change the screen size for a different device the magnifying effect has shifted to the right


Using enums for detecting object collisions As far as I know, I can detect what objects the player is colliding with is by the following code private void OnCollisionEnter2D(Collision2D collision) if(collision.collider.name.Equals("")) But I have heard that I can use enums instead to reduce computations. Could anyone explain to me using examples?


cant add script component So I'm just starting to try to learn unity development with C using this tutorial but I cant add the script to any game object and I get the following error Code of the script using System.Collections using System.Collections.Generic using UnityEngine public class NewBehaviourScript MonoBehaviour Start is called before the first frame update public Light myLight void Update() if (Input.GetKey("space")) myLight.enabled true else myLight.enabled false I know it's been answered before but I've done everything I read, I did my homework and I still cant get around this issue. I allready checked the name of the class and its the same as the file's name. I think it may be something regarding installation (?) I installed unity hub and it installed Unity and Microsoft Visual Studio by itself. Unity version 2019.3.3f1 MS Visual Studio version 16.4.5 MS Net Framework version 4.7.03062 I honestly dont know what else to do people! Please help!


Frequently change TextMeshPro text without garbage allocation? Is there a way to frequently change a timer display created with TMP, without it generating garbage? I'm currently using TMP.SetText(), which is supposed to not generate garbage, but it does.


Problem with default 3rd person controller in Unity 4 I am new to Unity. Whenever I am importing the default 3rd person controller (construction worker) in my scene and clicking the play button, the model seems to be in the running pose. The control keys are working properly, and I am also being able to make the character stand, walk, run and jump properly. Only problem is that it is always in the running pose which looks very odd. I did not make any change to anything. I just imported the controller as is. Can someone please tell me how to correct this issue? P.S. I hope my question was clear.


How to Use Initialize UDP (Unity Distribution Portal) I would like to use UDP (which stands for Unity Distribution Portal) in my game, but I have a problem with the Initializing. What i ve already done is Downloading Importing UDP from Unity Assets Store and setting up the connection between UDP and my game (with the Client ID) Now i would like if anyone can give me a detailed description what to do next, The description on the official Unity Website just confuses me...


How I can count how many time gameOver scene is loaded? I'm building a game using unity 3d and I want to add an interstitial ads to it, but I want it to appear after the player lost every 3 times. So when the player loses for the first time the ads will appear, and when he loses for the second and third time, nothing appears until he lost for fourth time.