If Statement executing wrong

Hey there, I have this bit of code that isn’t working how I’d expect it to. What should happen is, the code takes a bit of time before movesDouble becomes true. When I debug.log it shows both values preVal and newPosition taking about 10 seconds to reach 0 where they then reset back due to the Mathf.Repeat. Instead what is happening is the statement if (preVal < newPosition) is executing right away. I set the variable preVal to 100 when it’s made in MonoBehaviour. Does anyone know why the statement might be executing true before its meant to?

if (movesDouble == false)
        { 
            float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeX);
            transform.position = startPosition + Vector3.right * newPosition;
            if (preVal < newPosition)
            {
                preVal = 100;
                movesDouble = true;
            }
            preVal = newPosition;

edit (moved from “answer”):

@tormentoarmagedoom
Yes sorry, I accidentally missed it off when pasting it! Here’s the entire script, new to coding, I do apologise if it’s not great. The script is attached to 2 quads both at position 0,0,10 with a scale of 10,10,1. Scroll speed set to -2 and 10 on both. The movesDouble variable is set to true on one and false on the other. What happens when I press play is they both are set to false. I was following a unity tutorial for scrolling backgrounds but the tutorial didn’t show how to make a background that scrolled and then changed into different environments. I thought this would be a good way to do it, by having the quads alternate and when one snaps back to position I can change the background of it to the desired environment. If you know a better way to have a scrolling background where I can change the environment as it scrolls then let me know! Thank you :slight_smile:

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

public class BGScroller : MonoBehaviour
{
    public float scrollSpeed;
    public float tileSizeX;
    public bool movesDouble;
    float preVal = 100;

    private Vector3 startPosition;

	// Use this for initialization
	void Start ()
    {
        if (movesDouble == false)
        {
            startPosition = transform.position = new Vector3(transform.position.x - tileSizeX, transform.position.y, transform.position.z);
        }
        else
        {
            startPosition = transform.position = new Vector3(transform.position.x - tileSizeX, transform.position.y, transform.position.z);
        }
	}
	
	// Update is called once per frame
	void Update ()
    {
        if (movesDouble == false)
        { 
            float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeX);
            transform.position = startPosition + Vector3.right * newPosition;
            if (preVal < newPosition)
            {
                preVal = 100;
                movesDouble = true;
            }
            preVal = newPosition;
        }
        else
        {
            float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeX * 2);
            transform.position = startPosition + Vector3.right * newPosition;
            if (preVal < newPosition)
            {
                preVal = 100;
                movesDouble = false;
            }
            preVal = newPosition;
        }
    }
}

Good day @Demonolith !

The if statement is executing because preval is lower than newposition. Debug line by line when is executing, and read both variables. you need to check why preval is lower than newposition.

I’m sure is not a unity error “” XD just try to find where the code does this.

Where are you defining one of them to true and other one to false? If the variable is public, define it as true in the Start() function (to prevent the inspector to change it to false if you put false in the inspector). Is the only reason i can think a true variable can “become” false. Or there is some script doing it…

If this helps, upvote and mark the answers as good, if need more help, ask and give more info using @tormentoarmagedoom !

Bye :smiley:

You haven’t given us enough information for us to tell you exactly what the problem is. We can give you a list of possible problems and let you check each one, though.

Possibility #1: The if statement is being entered the second time this method is called, rather than the first.

Since you unconditionally assign preVal to be newPosition, one can only assume that preVal would be less than newPosition the second time this method is called. That would only not be true if subsequent calls to Mathf.Repeat were yielding ever-decreasing values.

Possibility #2: tileSizeX is large.

If tileSizeX is large enough, then a repeat (which really just seems to give you the remainder of a divide operation) would have a reasonable chance of yielding something larger than 100 on the very first call. For instance, if tileSizeX was about 1000, then there would be about a 90% chance that the number given by Mathf.Repeat was greater than 100.

There might be other possibilities but those are the ones I see.

Here is some code you can try. It demonstrates one way of moving something with the player. Since you mention snapping it will snap rather than have a smooth follow. I have used a tile, you could change that to your background.

Follow the instruction comments in first script.

CreateScene.cs

/*
 * To see this work just create a new project
 * and attach this script to an empty object.
 * 
 * If you plan to build it you will need to attach
 * it to a 3D object.
 * 
 * You can add scripts to the tile & player by
 * drag & drop in the inspector fields of this script.
 */

using UnityEngine;
using System;

public class CreateScene : MonoBehaviour {

    public UnityEngine.Object _tileScript;
    public UnityEngine.Object _playerScript;

    private GameObject _tile;
    private GameObject _player;

    private void Start()
    {
        CreateTile();
        CreatePlayer();
    }
    
    private void CreateTile()
    {
        _tile = GameObject.CreatePrimitive(PrimitiveType.Plane);
        _tile.name = "Tile";
        _tile.GetComponent<Renderer>().material.color = Color.black;
        if (_tileScript != null)
            _tile.AddComponent(Type.GetType(_tileScript.name + ", Assembly-CSharp"));
    }

    private void CreatePlayer()
    {
        _player = GameObject.CreatePrimitive(PrimitiveType.Capsule);
        _player.name = "Player";
        _player.transform.position += new Vector3(0f, 1f, 0f);
        _player.transform.rotation = Quaternion.Euler(0f, 180f, 0f);
        _player.AddComponent<Rigidbody>().useGravity = true;
        _player.GetComponent<Rigidbody>().constraints = (RigidbodyConstraints)122;        
        if (_playerScript != null)
            _player.AddComponent(Type.GetType(_playerScript.name + ", Assembly-CSharp"));

        GameObject visor = GameObject.CreatePrimitive(PrimitiveType.Cube);
        visor.name = "Visor";
        visor.transform.parent = _player.transform;
        visor.transform.localPosition = new Vector3(0f, 0.5f, 0.24f);
        visor.transform.localScale = new Vector3(0.95f, 0.25f, 0.5f);
        visor.GetComponent<Renderer>().material.color = Color.black;
    }
}

PlayerScript.cs

using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public float _maxDistance = 5f;

    private Transform _tile;
    private Vector3 _tileOffset;

    private void Start()
    {
        _tile = GameObject.Find("Tile").transform;
        _tileOffset = transform.position;
    }

    private void Update()
    {
        // turn player
        transform.Rotate(Vector3.up * Input.GetAxis("Horizontal"), Space.World);

        // move player
        transform.position += transform.forward * 3 * Input.GetAxis("Vertical") * Time.deltaTime;

        // move tile with player        
        Vector3 zeroPosition = transform.position - _tileOffset;
        float distance = Vector3.Distance(zeroPosition, _tile.position);
        if (distance >= _maxDistance)
        {
            // change environment
            _tile.position = Vector3.MoveTowards(_tile.position, zeroPosition, distance);
        }
    }
}

Fixed it with this code

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

public class BG_Scroll : MonoBehaviour
{
    public float scrollSpeed = 0.5f;

    public Texture ocean;
    public Texture oceanToCave;
    public Texture cave;
    public Texture caveToOcean;

    private Renderer rend;
    private float offset;
    private float reset;
    private bool oceanToCaveOn = false;
    private bool oceanOn = true;
    private bool caveOn = false;
    private bool caveToOceanOn = false;

    // Use this for initialization
    void Start()
    {
        rend = GetComponent<Renderer>();
    }

    void Update()
    {
        offset = reset += Time.deltaTime * scrollSpeed;

        rend.material.SetTextureOffset("_MainTex", new Vector2(reset,0));
        if (offset >= 1.00 && oceanOn == true)
        {
            reset = 0;
            OceanToCave();
            oceanOn = false;
            oceanToCaveOn = true;
        }
        else if (offset >= 0.66 && oceanToCaveOn == true)
        {
            reset = 0;
            Cave();
            oceanToCaveOn = false;
            caveOn = true;
        }
        else if (offset >= 1.00 && caveOn == true)
        {
            reset = 0;
            CaveToOcean();
            caveOn = false;
            caveToOceanOn = true;
        }
        else if (offset >= 0.66 && caveToOceanOn == true)
        {
            reset = 0;
            Ocean();
            caveToOceanOn = false;
            oceanOn = true;
        }
    }

    void Ocean()
    {
        rend.material.mainTexture = ocean;
        rend.material.mainTextureScale = new Vector2(1, 1);
    }

    void OceanToCave()
    {
        rend.material.mainTexture = oceanToCave;
        rend.material.mainTextureScale = new Vector2(0.333f, 1);
    }

    void Cave()
    {
        rend.material.mainTexture = cave;
        rend.material.mainTextureScale = new Vector2(1, 1);
    }

    void CaveToOcean()
    {
        rend.material.mainTexture = caveToOcean;
        rend.material.mainTextureScale = new Vector2(0.333f, 1);
    }
}