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

Comparing two gameobject prefabs or transforms on raycast?

Discussion in 'Scripting' started by Zymes, Dec 8, 2017.

  1. Zymes

    Zymes

    Joined:
    Feb 8, 2017
    Posts:
    106
    How do I compare a prefab placed in my scene vs one assigned in the inspector?

    I tried == and ReferenceEquals but the if statement is never true.

    This is my setup:

    1. A unit with a variable "public GameObject spawnPlane", I assigned the "spawnPlane" prefab to this slot

    2. A prefab in the scene that is a "spawnPlane" (where the unit will spawn on)

    3. I Physics.RaycastAll(transform.position, down, 50f) ... to look for this prefab in the scene. It finds it.

    4. I try to compare the units assigned spawnPlane vs the raycast (this does not work)

    Tried the following combinations:
    Code (csharp):
    1.  
    2. if (GameObject.ReferenceEquals(_hits[i].transform, unit.spawnPlane.transform)) { .. }
    3. if (GameObject.ReferenceEquals(_hits[i].transform.gameObject, unit.spawnPlane)) { .. }
    4. if (_hits[i].transform.gameObject == unit.spawnPlane) { ... }
    5. if (_hits[i].transform == unit.spawnPlane.transform) { ... }
    6.  

    But it never resolves to true.
     
  2. Tinglee82

    Tinglee82

    Joined:
    Jul 5, 2014
    Posts:
    3
    For item 1, did u assign the same spawnPlane GameObject from your scene (from item 2)? Or did u pull it from your prefab folder? Cos they are different instances.
     
  3. Zymes

    Zymes

    Joined:
    Feb 8, 2017
    Posts:
    106
    Yes I dragged the prefab from the project into the inspector, then dragged the same prefab into the scene itself.

    I am not sure you can compare the two because Unity thinks they are two different objects? I may be wrong, but I can't get it to work.

    I did a work around, and added a script component to my plane and used GetComponent<SpawnPlane> on it to see if it was a valid target.

    Maybe there is a solution for this problem however.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I think that adding a component was a good idea :)