I am making an endless runner game and I want to make the ground slightly increase in speed with time and I want the obstacles to move faster with the ground, I already made the ground move faster but I need to get the float from the ground script to the obstacle script because every time the obstacle respawns it’s velocity resets. i tried using GetComponent<MovingFloor>().groundVelocity;
but it didn’t work.
ground script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingFloor : MonoBehaviour
{
public float groundVelocity = 4.8f;
void Start()
{
StartCoroutine(speedIncrease());
}
void Update()
{
transform.position -= new Vector3(groundVelocity * Time.deltaTime, 0, 0);
if(transform.position.x < 0) transform.position += new Vector3(7, 0, 0);
}
IEnumerator speedIncrease()
{
while(true)
{
yield return new WaitForSeconds(2.5f);
groundVelocity = groundVelocity + 0.1f;
}
}
}
obstacles script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingObjects : MonoBehaviour
{
public float speed;
private Rigidbody2D rb;
private Vector2 screenBounds;
void Update()
{
speed = GetComponent<MovingFloor>().groundVelocity;
rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(-speed, 0);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(0.0f, Screen.height, Camera.main.transform.position.z));
if(transform.position.x < screenBounds.x * 2)
{
Destroy(this.gameObject);
}
}
}
unity error:
NullReferenceException: Object reference not set to an instance of an object
MovingObjects.Update () (at Assets/MovingObjects.cs:15)
hope that made sense