- Home /
Working with 2 scripts
Hi all, i am really new to unity and scripting and i am googling for this in last 2 days and i cant find answers. I have a problem with rotating object. I have a cube that i want to rotate constantly. In script that is on cube i have transform.Rotate function and it work great when i place it on void Update but i need to call it from other script with player.GetComponent().rotate();
and here is my problem, when i call it like this it rotate just 1 frame and then stop.I need it to keep rotating. I am sertainly doing something wrong but i just cant figure it out.
Here is script with rotation http://prntscr.com/hxhfam
Thank you for helping me in advance.
Answer by khiemngs · Jan 08, 2018 at 07:48 AM
Hi Milojko.
I see the problem you are facing is you don't completely understand how game work.
The game has big loop start from beginning to the end (when close game). Update method runs every frame, so when rotating in Update, it rotates every frame and you get what you want. When you move rotate to another method and call it, it just runs once when you call it.
I guess you want it to rotate if only you call a rotate and it keeps rotate in others frame after it. Try to create a bool to save rotate state.
bool isRotate = false;
void Update()
{
if(isRotate)
{
Rotate();
}
}
void BeginRotate()
{
isRotate = true;
}
void StopRotate()
{
isRotate = false;
}
void Rotate()
{
// Your code here
}
Thank you so much man, i am new in unity so i am still learning, you saved me, i just put my code in void BeginRotate and it is working.
bool isRotate = false;
void Update()
{
if (isRotate)
{
BeginRotate();
}
}
public void BeginRotate()
{
isRotate = true;
transform.Rotate(0, 0, speed);
Debug.Log("Radi");
}
void StopRotate()
{
isRotate = false;
}
}
You are welcome. :D At the beginning, I make the same mistake like that. I suggest you try to find out how basic game work. The game is an animated movie which every frame is rendered by code. :D
Answer by Ginxx009 · Jan 08, 2018 at 06:56 AM
Is this what you wanted.
1st script
void RotateObject(){
//transform.Rotate function
}
2nd script
public firstScript; //drag your first script here
void Update(){
firstScript.GetComponenent<NameOfTheFirstScript>(). RotateObject();
}
Thank you so much for helping but it isnt what i need, i need to call it when i swipe my finger up and i cant add void Update in that line. In my case it will do it just one frame and then stop