A list of a struct doesn´t saw a word in the console. Object reference, but i dont have anyone
Hi, I have a problem with this code, I'm a student, so, maybe it´s so simple, I don't now, I try maker simply, this is an example of my error:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour {
public struct StringContainer
{
public string value;
public void SetValue(string otherValue)
{
value = otherValue;
}
}
void Method()
{
List<StringContainer> stringContainers = new List<StringContainer>();
stringContainers.Add(new StringContainer());
stringContainers[0].SetValue("gato");
Debug.Log (stringContainers [0].value.Length);
}
// Use this for initialization
void Start () {
Method ();
}
// Update is called once per frame
void Update () {
}
}
the error is " Object reference not set to an instance of an object"
I don´t really understand
the error is in the Debug.Log line, or that sais the console
Answer by Bill9009 · Jun 12, 2017 at 01:33 AM
Don't ask such a vague question.
When you get an error like that you should also get the line number in which it occurred.
Why are you creating a list when you only want to use one StringContainer.
" Object reference not set to an instance of an object" occurs when you are attempting to use an object that has no value. This works:
void Method() { List<StringContainer> stringContainers = new List<StringContainer>(); stringContainers.Add(new StringContainer() { value = "gato" }); Debug.Log(stringContainers[0].value.Length); }
Sorry for this, my boss is asking me for this solution. I don´t do it like that. the error is in the " Debug.Log" line, I only wanna saw the word "gato" for the console, and I don´t understand why this not work
I try like you sais and don't work either
Then I'm not sure it worked on my end so i'm not sure. Did you replace the "$$anonymous$$ethod()" with $$anonymous$$e?
Your answer
![](https://koobas.hobune.stream/wayback/20220612123955im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Error!!! NullReferenceException: Object reference not set to an instance of an object 2 Answers
error CS1525: Unexpected symbol `float' 1 Answer
GameObject only spawning 60% of the time (c#) 1 Answer
Error with String in code 1 Answer
Create a copy of a non MonoBehaviour class and set variables from other class 0 Answers