- Home /
How do I make an instance of a class global???
Hi to all! I'm a newbie to OOP, coming from C. I just made my first class, but cannot figure out how to make an instance of it globally available. Here is a much simplified version of what I am trying to do:`
class Person{var name : String;}
static var person1 : Person;
person1.name = "Luke";
static var person2 : Person;
static person2.name = "Greg";
I know static doesn't work here. But I so wish it would! I need to list persons in a Person.js script, and access them from another script. Are singletons the answer? Help very much appreciated! G
Answer by Eric5h5 · Nov 06, 2011 at 03:26 AM
As long as a class is public, it's global. If you have this in one script:
class Person { // or "public class Person"; public is default in Unityscript
var name : String;
}
Then in any other script you can do
var person1 = new Person();
It's unlikely you want to make the variable static. That means there can only be one instance of it. You also probably want to make a constructor for the class, so you can do
var person1 = new Person("Luke");
If you're talking about the variable itself being global, the same thing applies. As long as it's public, it can be accessed from another script, usually by using a reference to the other game object in combination with GetComponent. See Accessing Other Game Objects in the docs.
Your answer
Follow this Question
Related Questions
How to list all the properties and methods from the class? 1 Answer
Instantiating objects from a class? (C#) 1 Answer
Update Function Won't Do If Statements 1 Answer
Static GameObject List gives error when calling Add or Count from another script 1 Answer
Can a class hear a broadcast message? 0 Answers