skip to Main Content

i’m fairly new to programming, and i have a problem with this code for my unity game, basically what happen is that the first time i try to call SelectGravity() it do it 2 or 3 times, after that it seems to work correctly, i can’t figure out why.

IsRotating = false is called in another script and i’m using visual studio 2019 for coding, if this can help.

void Update()
    {
        Rotation = Input.GetAxisRaw("RotatoWorld");

        if (Rotation != 0 && !IsRotating)
        {
            IsRotating = true;

            SelectGravity();
        }

        Physics2D.gravity = new Vector2(XGravity, YGravity);
    }

For those who asked this is the script in which i set IsRotating false

public IEnumerator Rotate90()
    {
        if(changeGravity.Rotation > 0.1)
        {
            Direction = 90;
        }
        else if(changeGravity.Rotation < -0.1)
        {
            Direction = -90;
        }

        float timeElapsed = 0;
        Quaternion startRotation = transform.rotation;
        Quaternion targetRotation = transform.rotation * Quaternion.Euler(0, 0, Direction);

        while (timeElapsed < lerpDuration)
        {
            transform.rotation = Quaternion.Slerp(startRotation, targetRotation, timeElapsed / lerpDuration);
            timeElapsed += Time.deltaTime;
            yield return null;
        }

        transform.rotation = targetRotation;

        StartCoroutine(CameraShake());

        changeGravity.IsRotating = false;
    } 

and i’ve declared it like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeGravity : MonoBehaviour
{
    CameraRotation cameraRotation;
    PlayerController playerController;

    private float XGravity;
    private float YGravity;
    public float Side;

    public float Rotation;
    public bool IsRotating;

    // Start is called before the first frame update
    void Start()
    {
        cameraRotation = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraRotation>();
        playerController = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();

        Side = 0;

        YGravity = -9.81f;
        XGravity = 0f;

        IsRotating = false;
    }

Other than this i don’t call this function or modify this variable anywhere.

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem was that the script was attached to more than one object, consequentially void update() were called two times per frame.


  2. Check the IsRotating boolean. It should modifying somewhere else or bool decleration function is not correct.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search