How to reference GameObject from script, C#

I’m spawning objects and would like to have reference to them stored in an array.
I have current instance of the object currentLoc which spawned on [x, y, 0] and would want him referenced in ArrayOfLocationPrefabs[x,y] for easy and orderly access.

GameObject currentLoc = (GameObject)GetComponent(name);

returns an error “Cannot convert type ‘UnityEngine.Component’ to ‘UnityEngine.GameObject’”, other takes on the problem also failed me.

Only working solution I have for this is to name all of these objects in their void Start() as (x.ToString() + y.ToString()) and later get them by GameObject.find (and possibly than reference them to the array).

I’m guessing there’s some basic way of getting on the GameObject to which a script is attached, that I’m missing.

1 Like

Your variables are kind of confusing (currentLoc as a GameObject and not a Vector3??), but I’ll give this a shot

First of all, you need to name your variable after the script. So say script is named ObjectScript, you would name your variable ‘ObjectScript currentLoc;’

Then you can assign what gameobject you want associated to this that also has that script. To do this, either give it a unique Tag or layer, or make the variable public and drag the gameobject into that variable in the editor. As an example, the Tag way would be:

currentLoc = GameObject.FindWithTag(“TAG”).GetComponent(); (this is the C# version btw). This method ONLY works if the object is unique aka there is only one of them. If there are two, it won’t know which one to choose. For that, you’ll need an array and a for loop.

I hope that at least partially answers your question. I had trouble figuring out what you were trying to do, but focused on correcting your line of code.

1 Like

Thanks for trying to figure it out, I’ve stated my problem in a wrong way. Next time I’ll really boil it down to basic, or just paste all of the code. (got to the bottom of this on my own, and it was pretty simple mistake)

BTW In this project I have empty game objects working as “locations” - “places” so they’re not Vector3. These “locations” are placed on a sphere as their longitude and latitude demands. However I still wanted to reference all of them with just x and y. I’ve tried to name them “xy” and then grab them by gameObject.Find(), but this seemed clunky way to do it, so I’ve tried to assign them spots on an array[,]… and got the above mentioned problem.

to answer your question: you just use this.gameObject to get the game object the script is running on.

if your trying to find a game object by name you would use a GameObject.Find overload.

GameObject is not a Component, thats why your getting the problem.