How to auto assign a script within a script?
Hi there,
I have made a script which spawns enemies and I have a Music Control script that I wanting to attach via inspector however it will not let me add the music control to the prefab so it is auto assigned when the enemies spawn. I have tried making an editor script which someone helped me on here before with and put
if((messaboutEnemyScript.musicSystem == null) && (GameObject.FindWithTag("Music Control") != null)) { messaboutEnemyScript.musicSystem = GameObject.FindWithTag("Music Control"); }
However I get the message "Cannot implicitly convert type 'UnityEngine.GameObject' to 'MusicControl'" of course as you cannot do that. Does anyone know how I would achieve auto assigning this?
Thank you so much for all of your help recently! @Mavina ,
Hi @gorevan,
Please send me all scripts involved
The script that does the spawning
The $$anonymous$$usic Control script
Any enemy scripts if it applies
Explain in detail what you want.
So far as I understand it, you would like a $$anonymous$$onoBehavior script (the $$anonymous$$usic Control script) to be attached immediately when an enemy is spawned (correct me if I am wrong).
I am also assu$$anonymous$$g the enemy is spawned at run time,
You can use pastebin.com to create links for each script.
Answer by TBruce · Dec 15, 2016 at 02:12 AM
From the error you posted, it looks like you are trying to assign a game object to a MusicControl. If that is all that the problem is try the following first to fix the error.
In place of your original code
if((messaboutEnemyScript.musicSystem == null) &&
(GameObject.FindWithTag("Music Control") != null))
{
messaboutEnemyScript.musicSystem = GameObject.FindWithTag("Music Control");
}
do this instead
if((messaboutEnemyScript.musicSystem == null) &&
(GameObject.FindWithTag("Music Control") != null) &&
(GameObject.FindWithTag("Music Control").GetComponent<MusicControl>() != null))
{
messaboutEnemyScript.musicSystem = GameObject.FindWithTag("Music Control").GetComponent<MusicControl>();
}
If you are still having problems please post all offending code as requested above.
Answer by Max_Bol · Dec 15, 2016 at 01:12 AM
We lack a bit of information for helping you out.
First, just for the case of being able to read your code, always put your code in coder tags. Like this :
if ((messaboutEnemyScript.musicSystem == null)
&& (GameObject.FindWithTag ("Music Control") != null)) {
messaboutEnemyScript.musicSystem = GameObject.FindWithTag ("Music Control");
}
That "101010" button is there for that purpose.
Now, the main problem we have at understanding your question is:
"What has to be attached to who?"
Should the Music Control script be attached to the Game Object that has the script which spawns the enemies or to the spawned enemies themselves?
Also, what is the messaboutEnemyScript referring to? We need the whole script to make sure we can help you out there. We can't just "guess" out of so little.