- Home /
Assign an instantiated GameObject?
Hi Unity people, i'm pretty new to Unity. I've a little problem (language currently using = c#)... I've created a class with a public GameObject into it(Highlightable.cs inherited from MonoBehaviour). When i try to access to it by another script it seems to work but when i'm instantiating the GO. Here's the code from another class:
GameObject go;
Transform casaAttuale;
Highlightable occupant;
for(int i=0;i<64;i++){
occupant = casaAttuale.GetComponent< Highlightable >();
if(-conditions-){
go = Instantiate (-prefab-,-position-,-rotation-) as GameObject;
//here we go
occupant.occupant = go;
}
}
occupant.occupant = go; doesn't work 'cause i made it public to see it on the Inspector but is always empty.... Here's another code that works instead:
void MoveHere(GameOBject newCasa){
Highlightable some = newCasa.GetComponent< Highlightable >();
-few lines of code-
some.occupant = _selected; //_selected is a GO declared in this class
-lines of code-
}
Why is this working and the other do not? Any answers? (Thanks in advice)
hey there! click "EDIT" and get all the code formatted nicely so people can help ok?
Answer by ScroodgeM · Sep 05, 2012 at 07:31 PM
this line
go = Instantiate (-prefab-,-position-,-rotation-) as GameObject;
will return you a GameObject type to 'go' only if '-prefab-' is GameObject. methinks it is Transform in your case. so you can use
go = (Instantiate (-prefab-,-position-,-rotation-) as Transform).gameObject;
type of object in Instantiate method and type that this method returns are the same.
Thanks very much man! You're right! That was blocking me from continuing the project. Thanks a lot.
Your answer
Follow this Question
Related Questions
Deleting a GameObject 2 Answers
prefab is instantiating without a script 2 Answers
How to add an asset to a script-enabled public game object? 1 Answer