-1

I am trying to get the name of the parent so that I can determine which button is pressed. However, it gives me:

The referenced script (Unknown) on this Behaviour is missing! Although all the names of the files are the same as the name of the class.

using System.Collections;

public class Buttons : MonoBehaviour
{
    private void Start()
    {
        Debug.Log(transform.parent.name);
    }
    
}

Edit: After running it twice, a new error appeared:

NullReferenceException: Object reference not set to an instance of an object Buttons.Start () (at Assets/Buttons.cs:8)

Dhrumil shah
  • 611
  • 4
  • 23
  • 2
    @nccsbim071 That's not how Unity works. A Monobehaviour instance will always have a transform. – frankhermes Jan 08 '21 at 16:11
  • @DeathWarrior990, try including "using UnityEngine;" at the top. – NCCSBIM071 Jan 08 '21 at 16:30
  • 1
    What if the object has no parent? – BugFinder Jan 08 '21 at 16:32
  • If you can't be sure an object will be non-null, you should first check it before you reference a member of that object: `Transform p = transform.parent; if (p != null) Debug.Log(p.name);` – Ruzihm Jan 08 '21 at 16:39
  • @Ruzihm in general you shouldn't use `!= null` though .. usually best in Unity would be `if(transform.parent) Debug.Log(transform.parent.name);` or in your example `if(p) ...` ;) – derHugo Jan 08 '21 at 19:20

1 Answers1

-2

Try Debug.Log(gameObject.transform.parent.name) as in following code in https://docs.unity3d.com/ScriptReference/GameObject-transform.html

using UnityEngine;

public class Example : MonoBehaviour
{
    void Start()
    {
        gameObject.transform.Translate(1, 1, 1);
    }
}

Also checkout https://docs.unity3d.com/ScriptReference/Transform.html.

Dharman
  • 30,962
  • 25
  • 85
  • 135
NCCSBIM071
  • 1,207
  • 1
  • 16
  • 30
  • 1
    Going through the additional reference of the `gameObject` or directly through `transform` makes no difference whatsoever. Also the translate is completely unrelated to OPs question .. the issue is rather that there simply is no parent ... – derHugo Jan 08 '21 at 19:19