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. Dismiss Notice

How do i create new reference from a gameObject.

Discussion in 'Scripting' started by Epic-Username, Dec 5, 2015.

  1. Epic-Username

    Epic-Username

    Joined:
    May 24, 2015
    Posts:
    339
    GameObject "a" wants to be a new reference from GameObject "b" doing "a = b" only sets "a" to get data from that specific GameObject("b") but when i delete that object then "a" and "b" is equal to null. I want to make "a" a new reference of "b" so when "b" = null "a" will be equal to something still. How would i do that i have tried "a = new b" but that gives me a error.
     
  2. bpeake

    bpeake

    Joined:
    Apr 8, 2013
    Posts:
    22
    How do you mean deleting? Do you mean engine side deletion or setting the reference to null?

    If you have the following code
    Code (CSharp):
    1. GameObject a = GameObject.Find("A);
    2. GameObject b = a;
    3.  
    4. a = null;
    Then at the end b will still be a reference to the original GameObject found.

    However if you have this code
    Code (CSharp):
    1. GameObject a = GameObject.Find("A");
    2. GameObject b = a;
    3.  
    4. Destroy(a);
    Then both a and b will appear null. The objects will still actually exist in memory like any other object in c# because there is no way to delete an object in C#, you just have to wait for the garbage collector to clean it up once there are zero references left to it. However it appears null because Unity because all objects that extend from the class UnityEngine.Object have been written so that there == operator will return true when compared with null if the object has been destroyed engine side.

    Hope that clarifies a bit.
     
    Kiwasi and Deleted User like this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    The other possible answer from the OP is you could be interested in making a copy. You can instantiate an existing GameObject to create a copy.