how to accsess sibling variables from a class.
i have code that looks like this
Public class attacking : MonoBehavior
{
public AudioSource audioSource;
// other variables
public class attack
{
//refrence to audiosSource in here
}
public attack[] data;
can i use the audio source without passing it to the class? if not, is there a way to automatically pass it to every instance of the class?
Answer by streeetwalker · Apr 16, 2020 at 03:48 AM
Hi @apallo13, Short answer: No. To access an object you have to have a reference.
The question is what are you trying to avoid? One line of code in the script that will assign the variable the reference?
Every instance of your game object will execute the same code. You don't have to do anything else. It is "automatic" ! Functions on instances are not copied, but exist in at one memory location.
You could make the variable static, so it would be shared by all instances of the class, but then the variable is not available in the inspector. And, you have to put in some check so that you are only assigning to one instance - otherwise you might as well make it non-static. And you potentially open yourself up to other problems - like if you burn that variable on one sibling you burn it on all.
You could put it as a static variable in another class, but then you have to define the other class, and you have to assign the variable in that class.
You could define it on a base class and make your siblings inherit from that base class, but same issues.
Any scheme you could come up with to avoid that one line of code is going to take more lines of code to deal with.
Now, if your talking about several lines of code to get your reference and you only want to run that code once, then it makes sense to move the code to another object - probably a Singleton, and create the reference there, and then give each sibling a reference to the variable through the Singleton.
[edit] Should add here that the Singleton itself is accessed through a Static reference without being declared as Static class. They have the convenience of Static access, but the payloads they carry, such as a references to other objects, don't have the dangers that static references do.[/edit]