I’m new to programming and unity and it keeps replaying this error code CS0236, for reference this is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Safe_Zone : MonoBehaviour
{
public float limitTime;
float unsafeTime = limitTime;
bool reached;
void Update () {
if (reached) { unsafeTime = limitTime; }
else { unsafeTime -= Time.deltaTime; }
if (unsafeTime <= 0f) {
void OnTriggerEnter(Collider other)
{
SceneManager.LoadScene(1);
}
}
}//Do something like destroy the player or show the gameover text, ...
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Player") { reached = true; }
}
void OnTriggerExit2D (Collider2D other) {
if (other.gameObject.tag == "Player") { reached = false; }
}
}
I’m trying to make where every ten seconds the player is transported into the game over scene, unless he is in a safe zone, I’m out of ideas to solve this.
Hey there and welcome to the forum,
there is a lot to unpack here regarding your script.
The error you posted is because of this:
float unsafeTime = limitTime;
It is not allowed to reference another variable (here limitTime
) during variable declaration unless that variable is marked as const
.
What you might want to do here is to assign the value of limitTime
into unsafeTime
during object startup.
float unsafeTime;
public void Awake() {
unsafeTime = limitTime;
}
In general, you have to make sure that you do not define functions inside of other functions. In your current version you declare void OnTriggerEnter(Collider other)
(which is a function) inside of Update
This is not allowed.
void Update () {
if (reached) { unsafeTime = limitTime; }
else { unsafeTime -= Time.deltaTime; }
if (unsafeTime <= 0f) {
}
}//Do something like destroy the player or show the gameover text, ...
void OnTriggerEnter(Collider other)
{
//do stuff here if a trigger-collider is hit.
SceneManager.LoadScene(1);
}
Apart from that you should decide you your game is 2D or 3D. You can either have 2D colliders or 3D colliders. Both together should not be used. (Not sure if it is possible but i’d advise to not do it anyways). A 2D Collider will never trigger OnTriggerEnter
and a 3D Collider will never trigger OnTriggerEnter2D
. Look at the components you are using and remove the wrong functions from your script.
Apart from this: Please make sure to use the code past tool when you make a post. (Little button with 1010101 on it above the text field.
When you post something regarding an error always make sure to post which line it points to → This is really important.