- Home /
Problem accessing public instances
I have a script called Status.js:
public class Character
{
public var name : String = "Teddy";
public var level : int;
public var hp : int;
}
public var teddy : Character = new Character();
public var mandy : Character = new Character();
I changed the name string of the second instance in the inspector:
Now I want another script (character_status.js) on another gameObject to access the instances name for example and to write it in the console, but I want to do that with just one line of code, because I'm currently creating a status-screen and there would be too much if-statements if I would do it different.
Before I set the Character class and the instances from static to public this worked:
var chara : Character = Status.teddy; // variable changeable from the menu
Debug.Log(chara.name); // and the Code does the rest
Now if I try to declare the variable chara like here this error comes up:
"An instance of type 'Status' is required to access non static member 'teddy'."
I tried so much to get an alternative way for it to work or to solve this declaration-problem but I just have no idea...
Hopefully someone here has! :D
Answer by Zymurer · Oct 18, 2019 at 03:55 PM
public var name : String = "Teddy";
As you must have noticed this line is what causes the error. Unity thinks it is static because you had given a value to that variable. Change this line to that:
public var name : String;
Then assign your varible. Hope that helped :D
Your answer
Follow this Question
Related Questions
Class and instances of the class question. 1 Answer
Creating class instances 1 Answer
Name instance String variable after instance? 0 Answers