Search Unity

Change the gamobject's material makes the game really slow

Discussion in 'Scripting' started by inicosia99, Jan 19, 2020.

  1. inicosia99

    inicosia99

    Joined:
    Oct 15, 2019
    Posts:
    90
    In my game at every tap the color of 3 different gameobject changes between vìblack and white. probably the script isn't good cause it makes the game really slow may you help me?

    Code (CSharp):
    1.   public Material materialb;
    2.      public Material materialn;
    3.      public bool colorblack;
    4.      int[] mat;
    5.      public static ColorChanging current;
    6.      void Awake()
    7.      {
    8.          if (current == null)
    9.              current = this;
    10.          else
    11.              return;
    12.      }
    13.      // Start is called before the first frame update
    14.      void Start()
    15.      {
    16.          colorblack= true;
    17.      }
    18.      // Update is called once per frame
    19.      void Update()
    20.      {
    21.          if (!BallMovement.current.gameOver && /*!PauseMenu.current.pause &&*/ MovimentoPalla.current.partito)
    22.              CahangeColor();
    23.      }
    24.      void ChangeColor()
    25.      {
    26.          if (gameObject != null)
    27.          {
    28.              if ((Input.GetMouseButtonDown(0) || Input.touches.Any(x => x.phase == TouchPhase.Began)) && !colorblack)
    29.              {
    30.                  GetComponent<Renderer>().material = materialn;
    31.                  colorblack= true;
    32.              }
    33.              else if ((Input.GetMouseButtonDown(0) || Input.touches.Any(x => x.phase == TouchPhase.Began)) && colorblack)
    34.              {
    35.                  GetComponent<Renderer>().material = materialb;
    36.                  colorblack= false;
    37.              }
    38.          }
    39.      }


    Thank you!
     
  2. Nyxal_Indie

    Nyxal_Indie

    Joined:
    Jun 26, 2019
    Posts:
    179
    There's a line error at 22: CahangeColor();
    Try to cache the component Renderer?
     
  3. inicosia99

    inicosia99

    Joined:
    Oct 15, 2019
    Posts:
    90
    CahangeColor();

    it's only a typing error cause I had to translate the code to make more comprensible for you.

    How can I cache the component renderer?
     
  4. Nyxal_Indie

    Nyxal_Indie

    Joined:
    Jun 26, 2019
    Posts:
    179
    Mi sembra che tu sia italiano quindi ti rispondo così. Per cachare un componente devi semplicemente dichiarare una variabile di tipo rigidbody: private RigidBody rgbd
    Poi nel metodo start fare: rgbd = GetComponent<RigidBody>()
    In questo modo potrai fare tutte le operazione che vuoi sul rigidbody utilizzando rgbd come ad esempio rgbd.AddForce
     
  5. inicosia99

    inicosia99

    Joined:
    Oct 15, 2019
    Posts:
    90
    Ma quale è la relazione tra il rigidbody e il renderer?