Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch state machines on the fly Unity C#

Having a little bit of an issue and cant seem to find an answer anywhere on the internet.

I have 4 sub state machines in Unity (see attached image), and upon play, if defaults to the pistol state machine and plays the idle animation fine.

I want to however have some code where by the user presses M, he can switch to the rifle sub state machine.

State Machines

I have tried animator.Play but that does not seem to do the trick, so I am bit stuck. The following does not work which i tried:

  if(Input.GetKeyDown(KeyCode.M))
    {
        animator.Play("Rifle",0);
    }   

Any ideas?

like image 459
Mubeen Hussain Avatar asked Nov 27 '25 11:11

Mubeen Hussain


2 Answers

Every Default button in unity has its own 'name' called input axes in which you can call (i.e "fire1","jump")

This could be very useful especially in Mobile applications where you set these buttons to operate each on-screen button in your virtual controller.

If you want to add new virtual axes go to the Edit->Project Settings->Input menu

see here

Here is an example almost similar to your code

var bullet : GameObject;
var shootPoint : Transform;

 function Update (){
     if(Input.GetKeyDown("Fire1")) || Input.GetKeyDown("space")){
      //example 
         Instantiate(bullet, shootPoint.position, tranform.rotation);

      //you could put the code on how you shoot here
      }

remember that update is called once every frame

Hope This Helps

like image 192
Kym NT Avatar answered Nov 30 '25 00:11

Kym NT


You can accomplish this by creating an integer parameter in your Animator. Then in your code, when you want to switch to another one, set the integer to a different value; each transition (white line) is assigned a different integer.

From code:

// in the class
Animator anim; // assign in Awake()

// in a function
if(Input.GetKeyDown(KeyCode.M)) {
    anim.SetInteger ("WeaponState", 2); // goes to Rifle
}

To work with this, you could create a None state machine as the default and get rid of Null. You would then have Any State point to None, Pistol, Rifle, etc.

like image 24
user3071284 Avatar answered Nov 30 '25 01:11

user3071284