0

I have a problem with my code in Unity and can't decide it by myself. Here is my code

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

[Serializable]
public class PlayerVoice
{
public int voiceSnap;
public string voiceValue;
}


public class GetVoice : MonoBehaviour
{
public static GetVoice instance;

public PlayerVoice[] playerVoice;
public int[] snaps;
public string[] voiceChangeValue;


public void Awake()
{
    instance = this;
}

public void LoadVoice()
{
        var count = MainInfo.instatnce.mainCount;
        playerVoice = new PlayerVoice[count];
        for (int i = 0; i < count; i++)
        {
            playerVoice[i].voiceSnap = snaps[i];
            playerVoice[i].voiceValue = voiceChangeValue[i];
        }
}
}

But in starting scene I get error in this line

playerVoice[i].voiceSnap = snaps[I];

this is error text from console

NullReferenceException: Object reference not set to an instance of an object GetVoice+d__43.MoveNext () (at Assets/Script/GetVoice.cs:36)

if I change playerVoice Length into inspector, the problem is resolved. I can't understand why I catch this error. Help please

Axel Vipovski
  • 95
  • 1
  • 7
  • `playerVoice = new PlayerVoice[count];` - You've create a new array of objects, but have put no objects in that array. It's just a placeholder for storing `PlayerVoice` objects. Essentially you need to create a new `PlayerVoice` object at any given index of `i` before you can use that object. – David Dec 15 '21 at 18:14
  • @David Thank you. How create a new `PlayerVoice` object at any given index of `I`? I thought that the object was already created – Axel Vipovski Dec 15 '21 at 18:25
  • 2
    `playerVoice[i] = new PlayerVoice();` – Ruzihm Dec 15 '21 at 18:26
  • 1
    I don't know for certain if this is the *ideal* approach since I'm not familiar with the architecture of designs here, but at its simplest it could just be `playerVoice[i] = new PlayerVoice();` as the first operation in your loop. (Assuming `PlayerVoice` has a parameterless constructor. Use whatever you would for creating a new instance of that object.) – David Dec 15 '21 at 18:26
  • Thanks to you, I figured out how it should work. Thank u – Axel Vipovski Dec 15 '21 at 18:34
  • Why don't you just configure them accordingly right in the Inspector? Instead of in the completely independent two arrays .. your class is already serialized anyway so why not directly use that? – derHugo Dec 15 '21 at 18:55

0 Answers0