- Home /
Using conditional logic when updating a text field (efficient code question)
Hi, hopefully a simple question. I just want to know if there's a more efficient way of writing the following example of code which updates a text field (and works fine):
// Just three static variables for this example
string cardname = "Examplecardname";
int damage = 0;
int block = 5;
readoutdisplay.text = "The card played was: " + cardname;
if (damage > 0)
{
readoutdisplay.text = readoutdisplay.text + "\n" + "It dealt: " + damage;
}
if (block >0)
{
readoutdisplay.text = readoutdisplay.text + "\n" + "It blocked: " + block;
}
I suspect the answer is no and that's fine. Any tips on ways to shorten the code down or just a straight up "That's about as good as it can be" is also fine. Thanks for your time.
Answer by Ironstone · Mar 14, 2021 at 12:10 PM
Not sure if this completely answers your question, but if your main interest is saving space, then it's worth pointing out that the {}
after the if
statement aren't required if it's one line long, so you can do
if (damage > 0)
readoutdisplay.text = readoutdisplay.text + "\n" + "It dealt: " + damage;
if (block >0)
readoutdisplay.text = readoutdisplay.text + "\n" + "It blocked: " + block;
if you really want. I also have a feeling that you can put the if
statements on one line, but in my personal opinion, the space you save isn't worth the readability you lose. Of course, it's up to you.
Cheers, I wasn't sure if there was any way to incorporate the if statements into the .text lines. I've not seen anything that supported it but just wanted to check (e.g. text.text=text.text + (if a>0)"something"+(if b>5)"something"). That kind of thing, but thats useful about not needing the { brackets for a single line and I agree about losing readability. Was just a little bored of writing readoutdisplay.text= over and over (i know, should have called it rd!)