Home > Net >  Can't access a property of an object if it's in an array
Can't access a property of an object if it's in an array

Time:12-16


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct Test {
    public string testString { get; set; }
    public Test(string TestString) {
        testString = TestString;

    }

}

public class arrayTest : MonoBehaviour {
    void Start() {
        object[] array = new object[2];
        Test tester = new Test("hello");
        array[0] = tester;
        Debug.Log(array[0].testString);

    }

}

I'm pretty new to C# so sorry if this is a stupid question. This is just a simplified version of my main program, but I keep getting the same error, which is

'object' does not contain a definition for 'testString' and no accessible extension method 'testString' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

It works fine if the object is not in an array, but once it is it gives me this. I've also tried to use TestString but to no avail. Any help would be appreciated.

CodePudding user response:

Your problem is here;

object[] array = new object[2];

Once in that array, your Test object is implicitly cast to a 'normal' object and thus you can only do things with it that you could to any normal object.

If you want an array of Test objects, do this instead;

Test[] array = new Test[2];

Or more succinctly,

var array = new Test[2];

CodePudding user response:

you have to cast object class to Test struct of tester, since array is an object class and doesnt have testString property

 Debug.Log( ((Test) array[0]).testString );

or define an array this way if you don't need to use any another classes

 Test[] array = new Test[2];
  • Related