- Home /
How can i make my function only assigned to and throw error otherwise?
I am real big on error prevention... sometimes I accidentally don't assign my function to a variable and things break and those errors are hard to sniff out, how can I make my function only be assignable?
//This is only example code
public int health = 100;
//This function must return a bool
//I made up the "assignOnly" type but I want something like that
assignOnly bool CheckIfDead()
{
if (health <= 0)
{
return true;
}
else
{
return false
}
}
public void TakeDamage(int damage)
{
bool isDead = false;
health -= damage;
//Right here my "isDead" bool is not assigned to CheckIfDead()
//How can i make CheckIfDead only an assignable function?
//So that lt throws an error if the function is not assigned to a bool
CheckIfDead();
if (isDead)
{
Die();
}
}
I'm sorry, but you have to be clearer. Please provide a code sample of a situation you are talking about
Answer by iagoccampos · Sep 12, 2020 at 11:06 PM
I didn't understand very well you question, but I will show some aproches:
First: Since your CheckIfDead returns bool, executes it inside "if"
private int health = 100;
private bool CheckIfDead()
{
return health <= 0;
}
public void TakeDamage(int damage)
{
health -= damage;
if (CheckIfDead())
Die();
}
Second: Using keyword ref
private int health = 100;
private void CheckIfDead(ref bool dead)
{
dead = health <= 0;
}
public void TakeDamage(int damage)
{
health -= damage;
bool isDead = false;
CheckIfDead(ref isDead)
if (isDead)
Die();
}
Answer by DarkWarriorZ · Sep 14, 2020 at 10:56 PM
@iagoccampos thats not exactly what I asked for but that does solve my problem, I wanted to make a function that returns a value and if I forget to actually assign my variable to that function it would throw an error... in order to not allow me to call that function without assigning it to something...
Also I'm aware of your optimizations for my code, I dumbed it down to make it more readable
BUT!! Long story short! Its impossible to call a function that uses the ref keyword without assigning that ref variable! Lol so you answered my question... thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220613011718im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
My function doesn't appears in the OnClick button script 5 Answers
How can i call a GUI function? 3 Answers
Distribute terrain in zones 3 Answers
GetComponent Picking up multiple scripts from differrent objects? 1 Answer