HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is there a better way to assign two variable to two others conditionally?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conditionallyotherswaybettertwotherevariableassign

Problem

I wrote this code, but it feels like it could be a bit more elegant:

Relevant code only:

GameObject newBall;
GameObject pathBall;
if (tag.Equals(pathBallTagName))
{
    newBall = other.gameObject;
    pathBall = gameObject;
}
else
{
    newBall = gameObject;
    pathBall = other.gameObject;
}


Entire .cs file:

```
using UnityEngine;
using System.Collections;
using BallDelegate;

public class BallCollider : MonoBehaviour {

public Spline mySpline;
private SplineController mySplineController;

public AllBallManager abm;

public string pathBallTagName = "PathBalls";
public string ballTagEnd = "Balls";

public BoxCollider front;
public BoxCollider back;
public BoxCollider spawnArea;

public string frontName = "BallBox Front";
public string backName = "BallBox Back";

public bool isInSpawn = true;

void Start() {
mySplineController = GetComponent ();
BoxCollider[] frontBack = GetComponentsInChildren ();
foreach (BoxCollider bc in frontBack)
if (bc != null) {
if (bc.name.Equals (frontName))
front = bc;
else if (bc != null && bc.name.Equals (backName))
back = bc;
}

}

void OnTriggerEnter(Collider other) {
if (mySplineController)
{
mySplineController.go = true;
if (mySpline)
mySplineController.gravSpline = mySplineController.currentSpline = mySpline;
}
if (other == spawnArea) {
isInSpawn = true;
}
else if (!isInSpawn) {
BallDelegateCS bd = other.gameObject.GetComponent();
if (bd) // only balls, no other game objects
{
GameObject newBall;
GameObject pathBall;
if (tag.Equals(pathBallTagName))
{
newBall = other.gameObject;
pathBall = gameObject;

Solution

One alternative, note how we must store the bool result to ensure identical semantics (otherwise you risk calling tag.Equals twice... which in addition to performance considerations might change its result between calls or have side effects!)

bool swap = tag.Equals(pathBallTagName);
GameObject newBall = swap ? other.gameObject : gameObject;
GameObject pathBall = swap ? gameObject : other.gameObject;


Alternatively one could implement a Swap function elsewhere:

GameObject newBall = other.gameObject;
GameObject pathBall = gameObject;
if (tag.Equals(pathBallTagName)) Swap (ref newBall, ref pathBall);

Code Snippets

bool swap = tag.Equals(pathBallTagName);
GameObject newBall = swap ? other.gameObject : gameObject;
GameObject pathBall = swap ? gameObject : other.gameObject;
GameObject newBall = other.gameObject;
GameObject pathBall = gameObject;
if (tag.Equals(pathBallTagName)) Swap (ref newBall, ref pathBall);

Context

StackExchange Code Review Q#48899, answer score: 6

Revisions (0)

No revisions yet.