M
M
maxemga2020-10-11 13:01:56
C++ / C#
maxemga, 2020-10-11 13:01:56

I can't get a function from another script, whyyy?

I have a script where objects are created and I need to access it through Another script so that when the player touches it, some actions happen to it (I'll throw off the code), but when I try to access it, the following error occurs

NullReferenceException: Object reference not set to an instance of an object
RandomSpawn.SpawnRandom () (at Assets/Scripts/RandomSpawn.cs:19)
PlayerController.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/PlayerController.cs:83)


https://jsfiddle.net/35a1dywL/ (here are the scripts at the link)

I googled and the point was that I did not initialize the object in the main class, I did it:
RandomSpawn Spawn = new RandomSpawn();
But this error still crashes ...
There are suggestions that it is necessary also initialize objects in this function, ie Coin and ListObjects Array
But how to do it?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawn : MonoBehaviour
{
    public GameObject[] listObjects;
    public GameObject Coin;
   

    int random;
    void Start()
    {
        random = Random.Range(0, listObjects.Length);  
        SpawnRandom();  
    }   
    public void SpawnRandom()

    {   
        Instantiate(Coin, listObjects[random].transform.position, Quaternion.identity);
    }
}


Must be inserted hereSpawnRandom

RandomSpawn Spawn = new RandomSpawn();
      
    private void OnTriggerEnter2D (Collider2D collision)
    {
    
      

        if (collision.tag.Equals("Coin"))
        {
            HealthBar.fill += 0.2f;
            Destroy(collision.gameObject);
            Spawn.SpawnRandom();
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Ascar, 2020-10-12
@maxemga

listObjects = new GameObject[] { new GameObject() };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question