- Home /
Enable script on parent
I am trying to get a script on the parent by a certain name and enable or disable it when there is a collision.
void OnCollisionEnter(Collision colliion)
{
transform.parent.GetComponent<scriptName>().enabled = false;
}
According to every other post I have read, this should work. But, the option to enable does not exist. What am I doing wrong?
scriptName is the name of a class and the script file it is in? It's inherited from $$anonymous$$onoBehaviour?
scriptName is the string name of the script to find.
Answer by kmeboe · Oct 08, 2012 at 07:34 PM
GetComponent returns type "Component", which doesn't have an "enabled" member. Try the following code (assuming your script's class name is "MyScript"):
void OnCollisionEnter(Collision colliion)
{
MyScript script = transform.parent.GetComponent("MyScript") as MyScript;
if (script)
script.enabled = false;
}
Also, perhaps more importantly, here is the answer for your other "problem":
http://www.oocities.org/safety4baby/images/ToddlerReins.jpg
:)
Tried the last part of the solution. I think there may be a problem with it. Now ins$$anonymous$$d of randomly smacking my keyboard it is flopping around like a fish while making strange keening noises. Please advise?
Hmm...I'm out of answers at this point, as I have the same problem myself. Perhaps we have to be satisfied with serving as an object lesson for others.
The better way to get a component in C# is:
transform.parent.GetComponent<$$anonymous$$yScript>()
The string version is significantly slower.
Right....$$anonymous$$ike's point is that the generic version of the method (<>) is faster -- good to know. The key portion of my above answer is the "As $$anonymous$$yScript" cast, which then allows you to access members of that class (or baseclasses).
Answer by OperationDogBird · Oct 06, 2012 at 06:56 AM
Im not an expert in c#, but i think it would look like this
transform.parent.GetComponent<scriptName>().enabled = false;
Just moved the () directly after the script name
Sorry, yes it is that way, sorry was typing it out with my toddler fighting for the keyboard. Will edit it.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
GetComponent keeps returning null 3 Answers
gameObject.GetComponent("Script").enabled = true not working 5 Answers