- Home /
Update within an if statement not working?
I need to use an Update method in an if statement, I know its inefficient, but it is necessary for this project, unfortunately though, I get this error; Error CS0103 The name 'Update' does not exist in the current context. This is my code;
public class BillboardScript : MonoBehaviour
{
public Transform BillboardCamera;
public bool UpdateEveryFrame;
public void Awake()
{
if (UpdateEveryFrame == true)
{
Update();
{
transform.LookAt(BillboardCamera);
}
}
else
{
Awake();
{
transform.LookAt(BillboardCamera);
}
}
}
}
Answer by Bunny83 · Jan 29, 2017 at 06:32 AM
You can't dynamically declare class methods inside methods. That's impossible from the very underlying class system.
If all that script is doing is to align the object "once" or every update, you can simply do:
public class BillboardScript : MonoBehaviour
{
public Transform BillboardCamera;
public bool UpdateEveryFrame;
void Start()
{
transform.LookAt(BillboardCamera);
if (!UpdateEveryFrame)
Destroy(this);
}
void Update()
{
transform.LookAt(BillboardCamera);
}
}
This will simply update your object every frame. However when "UpdateEveryFrame" is false the script destroys itself after the first alignment. If you need the object to be "resettable" you could simply set enabled = false;
instead of destroying the script. Though Awake and Start only run once in the lifetime of an instance so "resetting" makes not much sense.
Answer by whereswaldo · Jan 29, 2017 at 12:53 PM
try using void update instead of update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BillboardScript : MonoBehaviour
{
public Transform BillboardCamera;
public bool UpdateEveryFrame;
bool update = false;
public void Awake()
{
if (UpdateEveryFrame == true)
{
update = true;
}
else
{
Awake();
{
transform.LookAt(BillboardCamera);
}
}
}
void Update()
{
if (update == true)
{
transform.LookAt(BillboardCamera);
}
}
}
First the curly braces are useless but this is doomed.
If UpdateEveryFrame is true then call awake, in awake, if UpdateEveryFrame is true then call awake, in awake...
You get the idea?
Answer by ionside · Jan 29, 2017 at 01:24 AM
Why don't you use the bool in both Awake() and Update()?
Also, Awake() is always called before Update(), at the very start of your scene, your if/else statement just won't work.
void Awake(){
if(!UpdateEveryFrame)
transform.LookAt(BillboardCamera);
}
void Update(){
if(UpdateEveryFrame)
transform.LookAt(BillboardCamera);
}
I cant do this because it would still check the if statement is true every second and in this project I need everything to be optimized perfectly because this script will be ran hundreds of thousands of times, if not more.
I see, what if you create a second bool, which changes to true then the if statement can include check on the two bools?