- Home /
Help with assigning an object with Instantiate
I want to be able to call SetItem() from another script, and give it a GameObject. Then assign it to the GameObject myOb, and check it in Update().
It instantiates a new myOb ok, but is always null in Update(). What am I doing wrong?
private GameObject myOb;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(myOb != null)//currently always null
{
Debug.Log("Selected object is: " + myOb);
}
}
public void SetItem(GameObject newOb)
{
myOb = ((GameObject)Instantiate(newOb));
//myOb = newOb;
Debug.Log("New Object is: " + myOb);//prints "New Object is: Tree(Clone) (UnityEngine.GameObject)"
}
Does making myOb public ins$$anonymous$$d of private change anything?
This looks like it should work. You don't need the extra set of brackets here though:
myOb = (GameObject)Instantiate(newOb);
Is this class a mono-behaviour? If not, are you calling the correct instance, is the update function being called at all? What does the following code do in place of the update function?
void Update ()
{
Debug.Log("Selected object is: " + myOb);
}
I think this could be an instance problem, is the instance you are calling SetItem() on the same instance you are running Update() on? Can you show the code that calls SetItem()?
Thanks verenion, looks like it was an instance problem. Its fixed now, cheers guys.
Answer by Xtro · Aug 13, 2013 at 02:02 PM
Make sure your class inherits MonoBehaviour and it's attached to a gameobject in the scene.
You can't declare an Update function to a regular class (non-MonoBehaviour) and expect it to be called in the game update loop. It has to be a MonoBehaviour and be attached to a gameobject.
I said this 6 hours ago. This isn't an answer to the question anyway, not until we know exactly what he/she wants.
Oh sorry. I didn't read your comment because it wasn't an answer. So, I had my answer in my $$anonymous$$d and I wrote it as an answer. Now I look at your comment and it has few questions in it. $$anonymous$$ine was a statement which is more answerish than a question.
Your answer
Follow this Question
Related Questions
Create Texture2D and assign image to it through a script 1 Answer
Cannot assign script to objects when class is within a Namespace 1 Answer
Where are the built scripts stored in a build? 1 Answer
Assigning a gameObject in the script 3 Answers
Scripts won't automatically update, always need to 'reset' them in the inspector for update 11 Answers