Instantiating Prefab
Ok, not sure if my earlier post went through, but I am trying to have target follow my mouse position. I have
void Start () {
MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GameObject targetObject=(GameObject) Instantiate(target, new Vector3(MousePosition.x, MousePosition.y, 1), Quaternion.identity) ;
Debug.Log(targetObject);
}
void FixedUpdate () {
MousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//targetObject.transform.position = MousePosition;
Debug.Log(targetObject);
}
However, if I started with
public GameObject targetObject;
in the beginning, then targetObject is constantly Null for the debug. If I do not include that, then it says targetObject is not in the current context. I checked the library and I believe I Instantiated it right and targetObject should be a GameObject and not Null/not in context. What am I missing? Thanks!
Edit: Ok maybe my earlier post did went through and you can ignore this one....
Answer by Holy_Crapf · Jun 09, 2016 at 08:46 PM
Are you instantiating your global targetObject in start like you did when it was a local variable? Also, don't use FixedUpdate() for anything besides applying constant forces to rigidbodies. Use Update() instead.
Answer by btmedia14 · Jun 10, 2016 at 01:55 PM
When you declare targetObject locally, it is local to the Start() method only, not the class. So when targetObject is referenced in FixedUpdate() it is unknown (I suspect it should be a compile time error).
You say you started with public GameObject targetObject;
If that is declared as a class member then should be fine, unless the Instantiate itself is not returning a valid instance, hence resulting in a null value. But if the variable is still declared within Start(), it is still a local variable only.
Perhaps declare targetObject as a private class member.
Your answer
![](https://koobas.hobune.stream/wayback/20220612082538im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I spawn an array of prefab clones as children of an object? 1 Answer
My GetComponent is not working. 1 Answer
UnassignedReferenceException (Didn't find a solution) 1 Answer
UnassignedReferenceException: The variable has not been assigned, even though it has. - c# 3 Answers
Adding prefab object on collision to a another script 0 Answers