What are efficient ways to access other scripts ?
Hi, I started to wonder what are the best ways to access other scripts on different gameObjects. I know that Find() is very inefficient, but what about namespaces and static variables ? What advantages and disadvantages do they have ?
Answer by Landern · Aug 09, 2016 at 01:26 PM
Hold references when you create GameObjects of commonly used objects in general. This could be done through a manager class(singleton) or any number of different solutions/patterns. If you have references to your game objects you don't need to ask unity to find them, you can corrolate between the objects by reference or other identifiers on the objects and/or their sub-components attached.
Namespaces are find and don't do jack to you when you're referencing objects in memory, this is a code separation and isolation pattern in it's simplest terms.
Static or class members(as opposed to instance members(non-static)) generally solve an issue that could be better solved with something that isn't global in general. Static methods aren't all that bad, but static variables(fields/etc) on c# classes are generally used to fix something that exists because the person implementing doesn't understand how to manage their code base and takes the easy button way out. We see that all the time here on UA as it applies to holding and displaying scores.
So to reiterate...
When creating objects i know i'm going to be accessing to check properties or whatever about i would probably add it to a manager of sorts, again singleton is fine.
// Snip
public int numOfCreeps = 10; // default, inspector changable
public Creep creepPrefab; // attached in the inspector
SomeCreepManager scm = SomeCreepManager.GetInstance(); // will create or return a current instance of the SomeCreepManagerClass that is probably a static private variable internal to the class and junk
void Awake()
{
// Create creeps
for(int i = 0; i < numOfCreeps; i++)
{
Creep c = (Creep)Instantiate(creepPrefab, transform.position, transform.rotation);
scm.Creeps.Add(c);
}
}
Later i can access the SomeCreepManager.Creeps to collate collisions or whatever floats your boat.
Your answer
Follow this Question
Related Questions
Best way to communicate between scripts 4 Answers
I cant access a script that I made in Assets/Scripts from the FirstPersonCharacter script. 1 Answer
Reference Script In Other Script "type or namespace nae 'myScript' cannot..." 0 Answers
Static Array JS 0 Answers
Object reference not set to an instance of an object 0 Answers