General tips to shorten script length

Hey,

So lately I’ve been working on a bigger project than usual and scripts are getting rather long and I would like to shorten them.

I’ve been doing basic minor things like changing:

if(variable == True)
{
DoStuff();
}

to

if(variable)
{
DoStuff();
}

and instead of using tons of if/else statements I’m using switch statements instead but all these things seem pretty surface-level. Do you guys have any tips for me? To keeps scripts short and stay organized.

Thanks!

This is a very generic question to which the only answer is basically covering the entire syntax of C#.

Furthermore, shorter isn’t always necessarily better. Trying to one line something isn’t necessarily more efficient.

And lastly… the fact you were still doing:

if (someBool == true)

Says to me that your knowledge of the syntax of C# is very beginner, in which case… it’s probably easier for you to just pick up a book on C# rather than us writing a book in a forum.

1 Like

That’s indeed true, I do have some programming knowledge but I just learned it a bit ‘along the way’ and not really reading about syntax. I’m having a python class at uni though so that should help me a bit also even though they are completely different languages.

And I wouldn’t really say ‘very beginner’. I just never learned it by the book I think, which is of course not a positive thing.

Why don’t you post some block of your code that seems especially long or cumbersome or more repetitive than it should be to you, and we would be able to give advice based on that?

1 Like

Sure, like this block of code:

          if(HasTag)
          {
            if( other.tag == Tag) CorrectTag = true;
            else CorrectTag = false;
          }
          else CorrectTag = true;

          if(HasName)
          {
            if( other.name == Name) CorrectName = true;
            else CorrectName = false;
          }
          else CorrectName = true;

          if(IsLookingAt)
          {
            if(detection.InReach) CorrectView = true;
            else CorrectView = false;
          }
          else CorrectView = true;

          if(CorrectTag && CorrectName && CorrectView) StartCoroutine(doorpro.Move());
CorrectTag = (!HasTag || other.CompareTag(Tag));

CorrectName = (!HasName || other.name == Name);

CorrectView = (!IsLookingAt || detection.InReach);

if(CorrectTag && CorrectName && CorrectView) StartCoroutine(doorpro.Move());

Note, I use CompareTag because it’s more efficient on GC.

Also… if you don’t actually use the CorrectTag/CorrectName/CorrectView vars for anything but this block of code… it gets even shorter:

if ((!HasTag || other.CompareTag(Tag)) &&
    (!HasName || other.name == Name) &&
    (!IsLookingAt || detection.InReach))
{
    StartCoroutine(doorpro.Move());
}

I do use them elsewhere. This piece of code is actually really smart! Thanks!