Home > OS >  I can't get a variable into a collision method in C#
I can't get a variable into a collision method in C#

Time:09-01

I am making a script for a unity project to destroy an instantiated clone if it collides with another clone, but since the Game Object (the clone) is declared in the start method and I cannot put it at the top I need to figure out how to destroy the clone if it collides with something else.

This is the error I get if I put it on top:

A field initializer cannot reference the non-static field, method, or property

Code:

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

public class topbigspike : MonoBehaviour
{
     public GameObject Flame;
  
    // Start is called before the first frame update
    void Start()
    {
        int a = 30;
        int i = 0;

        while (0 < a) 
        {
            a--;
            i  ;
            GameObject FlameClone = Instantiate(Flame);
            FlameClone.transform.position = new Vector3(Random.Range(10, 2000), -3, 0);
        }
    }
 
    void OnCollisionEnter2D(Collision2D col) 
    {
        Destroy(FlameClone);
    }
}

CodePudding user response:

As the error message says, you cannot use Flame as field initializer. But you can still declare FlameClone as field (at the top, as you say) ) and initialize it in the Start method:

public class topbigspike : MonoBehaviour
{
     public GameObject Flame;
     public GameObject FlameClone; // <=== Declare here, as class field.
  
    // Start is called before the first frame update
    void Start()
    {
        int a = 30;
        int i = 0;

        while (0 < a) 
        {
            a--;
            i  ;
            FlameClone = Instantiate(Flame); // <=== Initialize here.
            FlameClone.transform.position = new Vector3(Random.Range(10, 2000), -3, 0);
        }
    }
 
    void OnCollisionEnter2D(Collision2D col) 
    {
        Destroy(FlameClone);
    }
}

CodePudding user response:

As already mentioned you need to store it a field in order to access it from other methods.

However, seeing a while loop there instantiating multiple (30) instances a single field isn't enough anyway except you really want to only destroy the last created instance.

It should probably rather be e.g.

public class topbigspike : MonoBehaviour
{
    public int amount = 30;
    public GameObject Flame;

    private GameObject[] flameInstances;
  
    void Start()
    {
        flameInstances = new GameObject[amount];

        for(var i = 0; i < amount; i  ) 
        {
            var flameInstance = Instantiate(Flame);
            flameInsance.transform.position = new Vector3(Random.Range(10, 2000), -3, 0);
            flameInstances[i] = flameInstance;
        }
    }
 
    void OnCollisionEnter2D(Collision2D col) 
    {
        foreach(var flameInstance in flameInstances)
        {
            Destroy(flameInstance);
        }
    }
}
  • Related