- Home /
Can't assign instantiated object to a variable
I'm trying to assign an instantiated object to a variable to be used in other parts of the script:
GameObject go;
GameObject go = Instantiate(circlePrefabs[i], NewPositions[randomIndex],
Quaternion.indentity) as GameObject;
go = go.gameObject;
But it nevers assigns it, go
stays null and Unity even warns me that it will always have its default value. What's going on here??
Edit: Renamed the variable, that seemed to fix it
Answer by unity_d25x5oKJtHA9qA · Jul 01, 2019 at 03:30 PM
Well, go is a GameObject, so I am not sure what you are trying to access whith "go.gameObject"
If you do
GameObject go = Instantiate(prefab, position, rotation);
you will get your GameObject in go, if you do Debug.Log(go.name); You should have the correct name.
Also, you don't need to cast a Gameobject as a GameObject, not repear the variable type. You could simplify your code by doing something like this :
GameObject go = Instantiate(circlePrefabs[i], NewPositions[randomIndex],
Quaternion.indentity);
I am instantiating inside of a forloop which is inside of an if statement which is inside of a function. The forloop runs 2 times, one time the instantiated object will have a positive position and the other time it will have a negative position, so to access these two outside of this specific function I made two variables outside of the function and assigned the instantiated object to one if it was positive, to the other if it was negative. but the outside variable had the same name of the variable that was inside (go) and that was probably causing trouble. So I changed the outside variable to goo, and kept the inside one as go. Sorry for this poopoo explanation though
Your answer
![](https://koobas.hobune.stream/wayback/20220612204141im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Mouse Over, Mouse Down, and Instantiate. 1 Answer
Problem trying to access values from another object script 0 Answers
Finding the Sum of Values of Multiple GameObjects in an Array + Variable Sized arrays 0 Answers
Passing variables to an instantiated object 1 Answer
When I instantiate a prefab, I want to assign it custom values. 1 Answer