Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.FindIndex Always Got Null in unity C#

I don't know why my script below in unity c# always got null ?

public class WeatherControl : MonoBehaviour {
    public GameObject Rain;

    public int[] RainTime = new int[]{6,7,8,9,10,18,19,20,21,22,16};

    int day;
    System.DateTime dates;

    // Use this for initialization
    void Start () {
        dates = System.DateTime.UtcNow;
        day = (int) dates.Day;
        //day = 16;
        Debug.Log ("DAY : " + day);
        int posRain = System.Array.FindIndex (RainTime, x => x.Equals(16));

        Debug.Log ("POS RAIN  : " + posRain);
        if (posRain >= 0) {
            Rain.SetActive (true);
        } else {
            Rain.SetActive (false);
        }

    }

}

my variable int posRain always return -1 Even at array there is value contain it. the variable day contain 16. I put it manually and type 16 too. But always return -1. I don't know why.

I have try this too :

int posRain = System.Array.IndexOf (RainTime, day);

That's always return -1 too.

I have tested it at online C# Tester here : https://csharppad.com/

It works at it return 10.

But in unity c# editor it is different always return -1.

Could someone explain what is going on ?

Thanks

Dennis

like image 221
Dennis Liu Avatar asked Feb 05 '26 01:02

Dennis Liu


1 Answers

Your array is public, so it's serialized by Unity. Unity will set the array to the value you gave it in inspector, overriding the one you declared in the code. If you don't need to access the array from the inspector, you should use [NonSerialized] attribute. If you do need to access it from inspector, you should also edit it from there.

like image 167
FINDarkside Avatar answered Feb 06 '26 15:02

FINDarkside



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!