- Home /
Getting acces to a script instance from a GameObject
He let us say that i have a GameObject in Unity and i associated an script to this object called Mover.cs in which i defined some properties can i access through the GameObject the instance of Mover associated to it?
Answer by Gardosen · Oct 20, 2014 at 11:06 AM
If you always need an Audio Source in your scenes, create a initScene, place a GameObject there, and attach a SoundConroller Script to it with all necessary AudioSources (eg. Background Music and SpecialEffects).
Set this Audio Controller as a singleton, and tell on a script DontDestroyOnLoad(GameObject); this way the EmptyGameObject with the Audio COntroller will exists in all scenes, and you can grab the audiosource you need over a getter setter system and replace the audio file, and tell audioSource.play();
this way you only have two sources which you can address, and you can be sure that they are existing, because they will stay over the whole gameclient in all scenes.
Greetings
Answer by Phantomized · Oct 20, 2014 at 08:52 AM
If I understand your question correctly then yes.
If you have your Mover.cs script on a GameObject as the component, and you want to access that instance from elsewhere:
Mover moverscript = GameObject.Find ("NameOfYourGameObject").GetComponent<Mover>();
Then you can access the members inside that script(as long as they are public) e.g:
moverscript.move();
There are many ways to get gameobjects and their components(which is an associated instance when talking about scripts) but this is one of the most simple ones.
Hi thanks for the reply, i did something like this, now the other problem that i am facing is that using an game-object from my prefabs is ok until it comes to an audio source, there was no way i could play my audio source from an instance of my prefab game object, it kept saying that the audio source is disabled has anyone deal with this problem? $$anonymous$$y solution was that i added a game object to the scene and played it each time but i don't like this approach... What would be the right way to do it?? imagine that your game object has sound that you want play like war cry or something that is individual for each instance....
Thanks.