- Home /
About scene change: is my method bad programming?
So, verbally, here's what I did: each frame, I check with a raycast if the character is facing a door and compare the tag of the door to determine which door leads to where. If, then, the player right clicks, then the game start a coroutine so it loads the new scene, then it waits for the scene to be loaded (and the screen to be faded out so it checks an other script), then it change the player's position.
In term of code, here's what we have:
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
rend.enabled = false;
if (Physics.Raycast(ray, out hit, interactDistance))
{
if (hit.collider.CompareTag("Door"))
{
rend.enabled = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
}
}
if (hit.collider.CompareTag("from_manor_to_forest"))
{
rend.enabled = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
StartCoroutine(FromManorToForest());
}
}
if (hit.collider.CompareTag("from_forest_to_manor"))
{
rend.enabled = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
StartCoroutine(FromForestToManor());
}
}
}
}
IEnumerator FromManorToForest()
{
Initiate.Fade("ForestPath", Color.black, 0.8f);
while (!Fader.startedLoading)
{
yield return null;
}
transform.parent.position = new Vector3(1f, 1.06f, 4f);
}
IEnumerator FromForestToManor()
{
Initiate.Fade("manor_scene", Color.black, 0.8f);
while (!Fader.startedLoading)
{
yield return null;
}
transform.parent.position = new Vector3(4.97f, 2.14f, 2.21f);
}
All this code is just basically to create a way in and a way out of a manor scene (to a forest scene). Let's say I add 10, or even 20 scenes. Are 20 or 40 raycast check, tag comparing, coroutines, etc. too impacting on performances?
Thank you for reading.
Answer by TheDavvyd · Nov 01, 2018 at 10:09 AM
You should generalize your code. I can think of two ways. 1) door holds scene name and position. And then you retrieve it from script. and pass it to Coroutine.
IEnumerator ChangeScene(string name,Vector3 pos){
Initiate.Fade(name,Color.black,0.8)
while(!Fader.startedLoading) yield return null;
transform.parent.position = pos;
}
2) Or door it self handles scene change in similar way.