A
A
Armyashka2020-02-13 18:37:14
C++ / C#
Armyashka, 2020-02-13 18:37:14

Why is there an error when trying to call a function after instantiating an object?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PieceMove : MonoBehaviour
{
    Rigidbody2D enemy;
    [SerializeField]
    private int EnemyForce;
    // Start is called before the first frame update
    void Start()
    {
        enemy = GetComponent<Rigidbody2D>();
    }
    // Update is called once per frame
    private void Awake()
    {
        Messenger.PlusListener("isMoveStart", isMoveStart);
    }
    private void OnDestroy()
    {
        Messenger.RemoveListener("isMoveStart", isMoveStart);
    }
    void Update()
    {
        
    }
    public void isMoveStart()
    {
        enemy.velocity = new Vector2(-EnemyForce, 0);
    }
}

Upon collision, an instance is created, and with it, start-of-motion errors already appear.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Instantiator : MonoBehaviour
{
    [SerializeField]
    private GameObject controller;
    [SerializeField]
    private GameObject pieceInstantiator;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "EditorOnly")
        {
            Destroy(collision.gameObject.transform.parent.gameObject);
            Instantiate(controller, pieceInstantiator.transform.position, Quaternion.identity);
            Messenger.Sirena("isMoveStart");
        }
    }
}

Error thrown: NullReferenceException: Object reference not set to an instance of an object
PieceMove.isMoveStart () (at Assets/Scripts/PieceMove.cs:30)
Messenger.Broadcast (System.String eventType, MessengerMode mode) (at Assets/Scripts/ Messenger.cs:175)
Messenger.Broadcast (System.String eventType) (at Assets/Scripts/Messenger.cs:161)
Instantiator.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/Instantiator.cs:31)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2020-02-13
@Armyashka

March to learn c#. And then Unity.
In fact, your enemy is empty, i.e. null. Why? Well, there are many options.
For example, GetComponent did not find the required component - it may simply not exist.
The second option (and quite possible) is that your isMoveStart callback jerked before Start. Look in the unit's manual for when Start is called and when Awake is called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question