Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Access to Script Component of an instanciated Prefab

Discussion in 'Scripting' started by Malgo, May 12, 2010.

  1. Malgo

    Malgo

    Joined:
    May 12, 2010
    Posts:
    2
    Hey everyone. I'm fairly new to unity and Ive hit a problem which I just cant seem to solve and it's driving me crazy... I hope someone can help me. :roll:

    Ive got a script attached to a gameobject that creates Instances of Prefabs dynamically during the game and removes them as well. Ive got another script attached to another gameobject which needs access to a script component of the created objects in order to do some crazy logic stuff with them during runtime.

    The problem I have is that I can't seem to find a way to access this script component I need to send it to the other class... Im probably using the GetComponent() function wrong here but I don't get the documentation regarding the function.

    Here's my code... I hope the error is obvious ^^

    Code (csharp):
    1.  
    2. // make a new prefab
    3. GameObject theobject = (GameObject)Instantiate(thePrefab, Vector3.zero, Quaternion.identity);
    4. // I add the object to a list inside the class to remove it later
    5. somelist.Add(theobject);
    6. //I try to get the componentscript from my newly created object, I suspect the error happens here
    7. TheScript actor = (TheScript) theobject.GetComponent(typeof(TheScript));
    8. //I get a null pointer exception here
    9. OtherClass.actors.Add(actor);
    10.  
     
  2. vatara

    vatara

    Joined:
    Feb 26, 2010
    Posts:
    22
    Are you using c#? If so I've done it like this:

    Code (csharp):
    1. theObject.GetComponent<TheScript>();
    2.  
     
  3. dbp

    dbp

    Joined:
    Mar 3, 2010
    Posts:
    324
    this message might be related to either OtherClass, actors or actor, you can do a simple check which one is causing this error by doing something like

    if(actor)
    {
    print("actor exists");
    }
     
  4. Malgo

    Malgo

    Joined:
    May 12, 2010
    Posts:
    2
    Thx for both your answers.

    @Vatara: Yes I'm using C#. Sadly I've tried that line of code already and it didn't work.
    Code (csharp):
    1. theObject.GetComponent<TheScript>();
    @dbp: The components are all there except for actor so I still think I'm using GetComponent wrong somehow.