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

Time:07-20

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!

CodePudding user response:

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.

  • Related