Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Unity prefab animator

Discussion in 'Scripting' started by ritendev, Apr 24, 2019.

  1. ritendev

    ritendev

    Joined:
    Jan 18, 2018
    Posts:
    12
    Hello,

    I've prefab (doors) with script and animator, I need to change bool of current prefab animator instead of all instances.

    Now when I change bool in 1 doors, all instances with this animator opens which is pretty funny :)

    How should I do that?

    Code (CSharp):
    1.  
    2.  
    3.     private Animator _animator;
    4.  
    5.  
    6.     void Start() {
    7.         _animator = gameObject.GetComponent<Animator>();
    8.  
    9.  
    10.     }
    11.  
    12.     void Update() {
    13.    
    14.  
    15.             openDoorAction();
    16.     }
    17.  
    18.     void openDoorAction()
    19.     {
    20.         if (Input.GetKeyUp(KeyCode.E))
    21.         {
    22.             _animator.SetBool("open_doors", !_animator.GetBool("open_doors"));
    23.         }
    24.     }
     
    Last edited: Apr 24, 2019
  2. ritendev

    ritendev

    Joined:
    Jan 18, 2018
    Posts:
    12
    Ok I've fixed it, by moving my openDoorAction method to distance check method and aditionally I check if player look at door by camera raycast

    Code (CSharp):
    1.     public Image icon;
    2.     public Text text;
    3.     private Animator _animator;
    4.     private GameObject player;
    5.  
    6.     void Start() {
    7.         _animator = gameObject.GetComponent<Animator>();
    8.         player = GameObject.FindWithTag("Player");
    9.  
    10.     }
    11.  
    12.     void Update() {
    13.      
    14.         checkDistance();  
    15.     }
    16.  
    17.     void openDoorAction()
    18.     {
    19.         if (Input.GetKeyUp(KeyCode.E))
    20.         {
    21.             _animator.SetBool("open_doors", !_animator.GetBool("open_doors"));
    22.         }
    23.     }
    24.     void checkDistance()
    25.     {
    26.         float dist = Vector3.Distance(player.transform.position, transform.position);
    27.         if (dist <= 1.5f)
    28.         {
    29.             showHint(true);
    30.             RaycastHit hit;
    31.             if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.TransformDirection(Vector3.forward), out hit, 2f))
    32.             {
    33.                 if (hit.transform.parent.parent.parent.name == transform.name)
    34.                 {
    35.                     openDoorAction();
    36.                 }
    37.             }
    38.         } else {
    39.             showHint(false);
    40.         }
    41.     }