Rotate 2D object 90 degrees with button
Hi,
I am trying to rotate a 2D object with the click on an UI button by 90 degrees. I created the UI button and linked its OnClick() to the public void TaskOnClick() in the object.
Somehow it is not changing the public float though which I am using in the rotation function in update.
It is returning the Debug.Log correctly....what am I doing wrong?
Any help massively appreciated! Cheers!
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems;
public class testObject_script : MonoBehaviour {
 public float RotateVal = 0;
 public void TaskOnClick(){
 
 Debug.Log ("Click");
 RotateVal = +90;
 }
 // Start is called before the first frame update
 void Start()
 {
  
 
 }
 // Update is called once per frame
 void Update()
 {
   Debug.Log ("RoateVal" + RotateVal); 
   GetComponent<Transform> ().eulerAngles = new Vector3 (0,0,RotateVal);
 }
}
Answer by Cronabot · Jul 17, 2020 at 06:06 PM
I know this is not exactly what you want, but I think a better way to do this in this case would be this:
 public void TaskOnClick(){
      Debug.Log ("Click");
      transform.Rotate(0, 0, 90)
 }
Cronabot, thanks for your swift reply. I have tried your suggestion, but to no avail. The object is still not rotating on Click of the button. I had to actually comment out the GetComponent ().eulerAngles = new Vector3 (0,0,RotateVal); as with that on, the Object just rotated 90 degrees once after starting the scene, on its own...
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems;
public class testObject_script : $$anonymous$$onoBehaviour {
 public float RotateVal = 0;
 public void TaskOnClick(){
 
 Debug.Log ("Click");
 transform.Rotate(0,0,90);
 }
 // Start is called before the first frame update
 void Start()
 {
  
 
 }
 // Update is called once per frame
 void Update()
 {
  // Debug.Log ("RoateVal" + RotateVal); 
  // GetComponent<Transform> ().eulerAngles = new Vector3 (0,0,RotateVal);
 }
}
Answer by olafmayer81 · Jul 18, 2020 at 10:43 AM
In addition I like to add that I am trying to control an instantiated prefab. I wasnt aware at first that that makes a difference. The script works fine with a static object from the hierarchy.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                