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

Simply Query about "this.name"

Discussion in 'Scripting' started by Joralin, Mar 8, 2015.

  1. Joralin

    Joralin

    Joined:
    Aug 27, 2014
    Posts:
    30
    Hello,

    In my code i created multiple prefabs. Then im checking an object for his name:

    Code (JavaScript):
    1. Debug.Log (this.name);
    Unity gives me so the item name, for example: "lion_prefab"

    I want to create an "if-statement" now and check for the item name.

    I tried this but it didnt worked:

    Code (JavaScript):
    1. if(this.name == "lion_prefab")
    2. {
    3. Debug.Log("thisIsAnLionPrefab");
    4. }
    What am i doing wrong?
     
  2. Dameon_

    Dameon_

    Joined:
    Apr 11, 2014
    Posts:
    542
    With strings, instead of ==, you need to use the Equals() method:

    if(this.name.Equals("lion_prefab"))
     
  3. Joralin

    Joralin

    Joined:
    Aug 27, 2014
    Posts:
    30
    Ok, i knew it would be simple. Thank you :)
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    It's not required to use Equals. In almost all cases, Equals and == have the same effect. (I seem to recall there's some difference if comparing null.)

    --Eric
     
  5. Joralin

    Joralin

    Joined:
    Aug 27, 2014
    Posts:
    30
    Yes your right, the problem was somewhere else. (Maybe because unity gives every prefab a hidden name , like "prefab0") I used the same query with "tag.name" and it works fine now.

     
  6. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Equals throws a null reference exception if the string is null. That's why you see Yoda conditionals in languages like Java where == doesn't work for strings.