Hello. I’m trying to instantiate a prefab at the mouseposition. I have dragged&dropped the unit1 prefab onto the empty field in the inspector window of the script, but when I run the game and click it gives me this error:
UnassignedReferenceException: The variable unit1 of ‘Movement’ has not been assigned.
You probably need to assign the unit1 variable of the Movement script in the inspector.
Any ideas how to solve this? Thanks in advance.
public GameObject unit1;
if (Input.GetButtonDown ("Fire1"))
Vector3 unitpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Instantiate(unit1, unitpos, Quaternion.identity);
You need to find the GameObject that actually has the Movement script attached to it as a Component. So under your Hierarchy view you will see Cube, GameObject, and MainCamera. One of those has the Movement script attached and if you click on it you will see it with an empty value for “unit1”. You will need to click and drag your prefab from your Project tab into the spot on that object’s Movement script in the Hierarchy tab. The Hierarchy tab shows you the GameObjects in the scene that are instanced and real.
I believe what you did is, you dragged the prefab into the default Movement script “unit1” variable instead of into the live Movement script on the GameObject that is actually in the scene. You need to set it specifically on the GameObject in the scene.