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

Question problem because of disabled object

Discussion in '2D' started by Folim, Jun 28, 2021.

  1. Folim

    Folim

    Joined:
    Nov 11, 2018
    Posts:
    1
    Object reference not set to an instance of an object

    This is happening because I leave the object disabled, and I want to activate it only when the player enters the room.

    public class Salas : MonoBehaviour
    {
    private Inimigo inimigo; // object disabled

    void Start()
    {
    inimigo = FindObjectOfType(typeof(Inimigo)) as Inimigo;
    }

    private void OnTriggerStay2D(Collider2D other)
    {

    if (other.CompareTag("Player"))
    {
    CameraController.instance.SetPosition(new Vector2(transform.position.x, transform.position.y));
    >>>> inimigo.ativar = true;

    }
    }

    }
     

    Attached Files:

  2. Unrighteouss

    Unrighteouss

    Joined:
    Apr 24, 2018
    Posts:
    599
    Hey,

    If you want the object to start disabled, the best way to get a reference to it is before runtime. Here is an example:
    Code (CSharp):
    1. {
    2.     [SerializeField] private Inimigo inimigo;
    3. }
    Drag the object into the field in the inspector, then you'll be able to reference it even though it starts disabled.
     
  3. Tyrant7

    Tyrant7

    Joined:
    Aug 15, 2019
    Posts:
    34
    As @Unrighteouss said, you can use the SerializeField attribute, or make the variable public to show it in the inspector.

    Code (CSharp):
    1. [SerializeField] Inimigo inimigo;
    2.  
    3. public inimigo inimio
    Another note I thought I would mention is that in C# you can simply put "FindObjectOfType<Inimigo>;" instead of having to specify using the "as" keyword.