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

Reference Script Object

Discussion in '2D' started by RedKinetic, Apr 9, 2015.

  1. RedKinetic

    RedKinetic

    Joined:
    Nov 9, 2014
    Posts:
    20
    I have two prefab objects saved to be instantiated at random intervals.

    I want to alter the speed of these objects. I have Speed as a public variable inside a Script attached to that Prefab. I want to access that Scripts variable for separate prefabs (different tags), to change them through the game.
    I tried:
    GameObject enemyManagerScript = GameObject.Find("EnemyManager");
    enemyManager = enemyManagerScript.GetComponent<EnemyManager>();
    I tried 'Finding' the name of my prefab with no success.

    Error: Instance not set to object.
    The Script and its variable are only attached to the prefab and not a persisting game object in the Scene.

    Thanks
     
  2. ritesh_khokhani

    ritesh_khokhani

    Joined:
    Jun 26, 2013
    Posts:
    47
    Hey,

    I think you have to check for null reference before getting script component EnemyManager,
     
  3. biowinter

    biowinter

    Joined:
    Dec 10, 2011
    Posts:
    34
    Hey RedKinetic,

    When you instantiate a Prefab, it will have in its name the words "(Clone)"
    Is EnemyManager one of the Prefabs? If so look for it as "EnemyManager(Clone)"
    Another way to be sure is to call this on the script start function.

    Code (CSharp):
    1.     void Start () {
    2.         print(gameObject.name);
    3.     }
    If you have more than two with the same name, you will be unable to access the other one with the GameObject.find() function. You could use then GameObject.FindWithTag().
    If you are going to call this every time you instantiate them, you should instead store these two prefabs in public variables and send them to a gameobject pool, and bring them back as needed.

    Read here: http://docs.unity3d.com/ScriptReference/GameObject.Find.html
     
  4. Leo-Yaik

    Leo-Yaik

    Unity Technologies

    Joined:
    Aug 13, 2014
    Posts:
    434
    Hi

    GameObject.Find looks for the GameObjects that are in the scene.

    For your case, 1 way to do it is
    1. Create a folder call Resources
    2. Place your prefab in the folder
    3. Use Resources.Load and instantiate the object.
     
  5. chazzysb

    chazzysb

    Joined:
    Jan 8, 2015
    Posts:
    6