Hiya all,
I recently started getting into game dev as a hobby (so that means I am a total noob, please be patient with me).
I am in the process of building a 2nd Level for my online coursework-game and I am trying to achieve the following:
-
A second platform to appear after X time (which is a public variable). The code is attached to the second platform and it works.
-
The barrier in front of the second platform to be destructible by shooting at it, but ONLY after the second platform appears. The script is attached to the barrier and it doesn’t work. What happens is that the barrier can be destroyed from the moment the game starts, so it seems that the system doesn’t check for the other requirement.
Also I get the following error on the Unity code:
“UnityException: FindGameObjectWithTag is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour ‘DeactivateBarrier’.
See “Script Serialization” page in the Unity Manual for further details.
DeactivateBarrier…ctor () (at Assets/Scripts/DeactivateBarrier.cs:9)”
I have tried a few iterations of the code, trying to get the code to look for the time the second platform appears, or looking for if the platform appears. I also tried to move whatever code has the FindGameObjectWithTag inside the Start class but without any luck.
Below I have attached two variations of the same code. Any help will be appreciated. Thanks!
Variation No. 1
public class DeactivateBarrier : MonoBehaviour
{
private GameObject movingPlatform = GameObject.FindGameObjectWithTag("MovingPlatform");
public void Update()
{
if (movingPlatform == true)
{
Invoke("OnCollisionEnter", 0);
}
}
void OnCollisionEnter(Collision collision)
{
if(GameObject.FindGameObjectWithTag("Projectile"))
{
Destroy(gameObject, 0);
}
}
}
Variation No. 2
public class DeactivateBarrier : MonoBehaviour
{
//reference for the time variable from the MoveToNextPlatform Script
private float timeForDestruction = GameObject.Find("Second Platform").GetComponent<MoveToNextPlatform>().secondsToAppear;
public void Update()
{
if (Time.timeSinceLevelLoad >= timeForDestruction)
{
Invoke("OnCollisionEnter", 0);
}
}
void OnCollisionEnter(Collision collision)
{
if(GameObject.FindGameObjectWithTag("Projectile"))
{
Destroy(gameObject, 0);
}
}
}