Search Unity

How to open a Box with C# script

Discussion in 'Scripting' started by anme2018, Oct 4, 2019.

  1. anme2018

    anme2018

    Joined:
    Apr 10, 2016
    Posts:
    13
    Hi,

    i try to open a box upwards with a script. Unfortunately the box only opens but not closes.
    Can somebody tell me please where the mistake is, I just can't find it?

    Here is the code:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DoorOpener : MonoBehaviour {
    6.  
    7.     float speedOfRotation = 1.5f;
    8.     float openDegree = 90.0f;
    9.     private bool open;
    10.     private bool enter;
    11.     private Vector3 openRotate;
    12.     private Vector3 closeRotate;
    13.  
    14.  
    15.     void Start()
    16.     {
    17.         closeRotate = transform.eulerAngles;
    18.         openRotate = new Vector3(closeRotate.x + openDegree, closeRotate.y, closeRotate.z);
    19.  
    20.     }
    21.  
    22.     void Update()
    23.      {
    24.  
    25.  
    26.  
    27.          if (open)
    28.          {
    29.              transform.eulerAngles = Vector3.Slerp (transform.eulerAngles, openRotate, Time.deltaTime * speedOfRotation);
    30.  
    31.        
    32.          }
    33.          if (enter)
    34.          {
    35.              open = true;
    36.          }
    37.  
    38.     }
    39.  
    40.      private void OnTriggerEnter (Collider other)
    41.      {
    42.          if (other.gameObject.tag == "Player")
    43.          {
    44.  
    45.              enter = true;
    46.          }
    47.      }
    48.  
    49.  
    50.  
    51.  
    52.     void OnTriggerExit (Collider other)
    53.     {
    54.         if (other.gameObject.tag == "Player")
    55.         {
    56.  
    57.             enter = false;
    58.         }
    59.     }
    60. }
    61.  
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    It is because there's no code to close the box and to reset open flag back to false.
    Get rid of that flags. in trigger enter and exit set target rotation to open and close rotations respectively, then in update lerm current rotation to target.
     
  3. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    Code (CSharp):
    1. void OnTriggerExit (Collider other)
    2.     {
    3.         if (other.gameObject.tag == "Player")
    4.         {
    5.             enter = false;
    6.             open = false; // Maybe adding this will help?
    7.         }
    8.     }