Hello, I’m new to learning C# and Unity, and I’ve managed to figure out most things with the help of the documentation, tutorials and general googling, but I can’t seem to figure this out.
My problem is I want to disable a script, that is on a child object of the current object and script, but I can’t figure out how to.
The way I have it set up, is when the user presses “1” to switch weapons it disables the gameObject after 1 second to allow for the animation of swapping to play, but for that 1 second the script on that gameObject is still active.
So my question is, how do I disable that script immediately?
Basically my code looks like this
public GameObject Weapon1;
public IEnumerator WeaponSwap() {
weaponSwap = !weaponSwap;
yield return new WaitForSeconds(1f);
Weapon1.SetActive(weaponSwap);
yield break;
}
if (Input.GetKeyDown (KeyCode.Alpha1))
{
StartCoroutine(WeaponSwap());
}
I know I need it in the if statement, but what I actually need to write to direct it to the script component I haven’t been able to figure out.
Ok, I know that my answer here is going to be way difficult for a beginner, but nonetheless I think it’s a good idea to write down the best practice to obtain the desired result.
Waiting 1 second is not correct: different weapons will have different animations and timing will be off. The correct way to do this is to setup an event at the beginning of the animation and another one at the end of using the animation inspector to add the events.
Once you have the events setup all you need is a script with methods having the same name of the events you setup attached to the same object the animator is on. This will allow you to have a perfect sync, to know when the anim starts (to disable the script) and when it ends (to replace a weapon with another).
You don’t have a reference to your child object’s script anywhere in your script.
What you should do is get a reference to the other script and cache it in a variable like this:
transform.GetChild(0) seeks out the first child object of the object the script belongs to. An index of 1 would get the second etc.
Alternatively you can transform.FindChild("name") to get the object by name.
GetComponent<OtherScriptName>() looks for a script (or component) on a given game object and returns it. Note that this function should rarely be used in the update loop as it can be quite performance intensive.
To then disable the script you can simply use myOtherScript.SetActive(false);; in your case before the yield return of your WeaponSwap coroutine.
You want to first disable the script on Weapon1, wait one second and then disable the Weapon1 game object? I don’t know what your script is called so I called it Foo here. Change it to your actual script name.
Foo foo = Weapon1.GetComponent<Foo>(); // If you don't already have a reference to it...
foo.enabled = weaponSwap;
yield return new WaitForSeconds(1f);
Weapon1.SetActive(weaponSwap);