Raziel
Raziel

Reputation: 1566

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?

Upvotes: 3

Views: 1390

Answers (2)

user3071284
user3071284

Reputation: 7100

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.

Upvotes: 1

Kym NT
Kym NT

Reputation: 790

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

Upvotes: 1

Related Questions