- Home /
RequireComponent only blocks removal? Can I force a warning if missing at runtime?
Hi
I have several scripts I want associated with a GameObject and I don't want that GameObject to exist in the scene without these components.
As such I have attached a script to that GameObject which has a bunch of:
[RequireComponent (typeof(ScriptName))]
However, if I run the game without those required components I don't even get an error. If I add the component and try to remove it, I get an error message and it wont let me. But, there is no safegaurd/warning if they required component is never added.
Is there a way I can FORCE an object to get scripts added to it if its missing from the required (ideally in the IDE and not in the code)?
RequireComponent
is supposed to add the required components when you attach the script in edit mode. Is this not what you're experiencing?
Correct. It wont let me remove it when I add the component, but if I add a script with requires, those requires are not automatically added
Answer by Nymisu · Feb 23, 2015 at 08:19 AM
Um...
ScriptName mahscript;
void Start();
{
mahscript = ***.getComponent<ScriptName>();
if (mahscript == null) Debug.Error("Oh no!");
}
Additionally, you can do this in editorscript too, if you'd like.
Yes, perhaps I was unclear, I was hoping to have these added when I drag the script on to the object, not at runtime.
In that case, use an editorscript that does that if GetComponent() returns null. Don't feel put off by the complexity of editorscripts, all you really need to is:
//this goes in the "Editor" folder
public class YourscriptsEditor : Editor {
private yourscript x;
private static bool addedthat = false; //optimization
OnInspectorGUI()
{
if (x == null) x = (yourscript)target;
if(!addedthat)
{
if (x.getComponent<componentyouwant>() == null) x.gameObject.AddComponent<componentyouwant>();
addedthat = true;
}
//and then draw as normal
DrawDefaultInspector ();
}
}