Reputation: 21
I'm trying to make a platformer with two characters and I want it so when they touch it goes to the next level. however, it instantly teleports me to the end of the game help!! I'm new to coding so don't judge lol.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mrglobtransform : MonoBehaviour
{
private int level;
public GameObject player;
private bool update;
private void Start()
{
level = 1;
}
IEnumerator waitforknees()
{
yield return new WaitForSeconds(0.4f);
update = false;
}
void knees()
{
if (update == true)
{
if (level == 2)
{
player.transform.position = new Vector3(-42.75f, -31.97f, 0);
GameObject.Find("Main Camera").GetComponent<cameramove>().player = 2;
}
if (level == 3)
{
player.transform.position = new Vector3(-7.43f, -196.2f, 0);
GameObject.Find("Main Camera").GetComponent<cameramove>().player = 2;
}
StartCoroutine(waitforknees());
return;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 8)
{
Debug.Log("sd hfjsgbchgbvds hgvn");
knees();
if (level == 1)
{
level = 2;
}
if (level == 2)
{
level = 3;
}
update = true;
}
}
}
ignore the names I'm uncreative. im new to coding there's probably an easy fix that I'm missing.
Upvotes: 0
Views: 91
Reputation: 90629
So some issues here.
First of all
if (level == 1)
{
level = 2;
}
if (level == 2)
{
level = 3;
}
this means if your level
at the top is 1
or 2
it will always be 3
at the end because both cases will be executed sequencially.
You rather want to do e.g.
level++;
// top it to 3
level = Mathf.Min(level, 3);
Then you are setting update = true
after calling knees
.. so most probably nothing will ever happen at all.
Why not simply do
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 8)
{
Debug.Log("sd hfjsgbchgbvds hgvn");
level++;
// top it to 3
level = Mathf.Min(level, 3);
knees();
}
}
void knees()
{
switch(level)
{
case 2:
player.transform.position = new Vector3(-42.75f, -31.97f, 0);
GameObject.Find("Main Camera").GetComponent<cameramove>().player = 2;
break;
case 3:
player.transform.position = new Vector3(-7.43f, -196.2f, 0);
GameObject.Find("Main Camera").GetComponent<cameramove>().player = 2;
break;
}
}
Upvotes: 1