简体   繁体   中英

How can I run a method on one script from another? [UNITY 3D] C#

I have 2 scripts: WeaponAttack and an AnimationEventManager.

this is the 2 methods from WeaponAttack

public void EnableCollider()
    {
        
        Debug.Log("collider enabled");
        isAttacking = true;
    }
    
    public void DisableCollider()
    {
        
        Debug.Log("collider disabled");
        isAttacking = false;
    }

and these 2 methods are from the AnimationEventEditor

public void StartAttackCollider()
    {
        
        weaponAttack.EnableCollider();
         
    }

    public void StopAttackCollider()
    {
        
        weaponAttack.DisableCollider();
        
    }

Id like to use animation events to turn the box colliders on and off using the Enable and Disable Collider methods inside of WeaponAttack but with what I currently have written I get an object reference error that weaponAttack is not set to an instance of an object. Ive been scratching my head at this all day and can't figure out what I should do lol, if you know how I can fix this pls lmk! thanks!

This means that the variable weaponAttack does not have a value, which means that nothing is written there. You need to let the AnimationEventEditor know what weaponAttack is.

Two simple ways of doing this:

  1. make weaponAttack a public variable and set it in the editor.

In the AnimationEventEditor, write:

public WeaponAttack weaponAttack;

Then, find the script in the unity editor (as attached to a Game Object), and drag the correct WeaponAttack script into the box labelled weaponAttack. (If your WeaponAttack is part of a different gameobject, drag the gameobject it is attached to)

  1. Use GetComponent This requires both scripts to be components of the same GameObject. If they are, you can set weaponAttack like this:

    weaponAttack = GetComponent<WeaponAttack>()

This will set weaponAttack to mean the WeaponAttack script attached to the same GameObject.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM