79761

C# & Unity : Pass reference by value?

Question:

I'm new to C# and Unity, and here I am tweaking and creating my first minigame.

Here is the problem:<br /> I've got a little cube, that moves. I've implemented a method that checks the next position before making a move. The method receives as parameters the current cube position, and the direction:

public bool okToMove(Transform playerCurrentPosition , int directionIndex) { Transform playerNextPosition = playerCurrentPosition; playerNextPosition.Translate(toDirection(directionIndex)); if (playerNextPosition.position.x > 1 || playerNextPosition.position.x < -1 || playerNextPosition.position.y > 1 || playerNextPosition.position.y < -1) return false; else return true; }

Then, I call the method

public void movePlayer(int directionIndex) { if ( okToMove(gameObject.transform, directionIndex) ) transform.Translate(toDirection(directionIndex)); }

The problem is that the cube makes 2 moves at once. This is because of

transform.Translate(toDirection(directionIndex));

and

playerNextPosition.Translate(toDirection(directionIndex));

that is called from okToMove method. Unity or C# sees playerNextPosition as the real cube, and not somekind of temporary copy that only exists inside the method.

So why is my gameObject.transform being passed as a reference and not by value? How can I make it work?

Thanks in advance and sorry for my noobiness.

Answer1:

You are passing reference to Transform and then moving it with translate in "okToMove", best way is to make a copy of Vector3, just change your "okToMove" like this.

public bool okToMove(Transform playerCurrentPosition , int directionIndex){ Vector3 playerNextPosition = playerCurrentPosition.position; playerNextPosition += toDirection(directionIndex); if (playerNextPosition.x > 1 || playerNextPosition.x < -1 || playerNextPosition..y > 1 || playerNextPosition.position.y < -1) return false; else return true; }

Transform is component attached to each gameObject and it holds values for position, rotation and scale, so your "playerCurrentPosition" is not copy of position but rather reference to Transform (not a copy).

Answer2:

Create a new GameObject that is a copy of yours original, and use its transform to make your calculations. (This answer is originally from the <a href="http://answers.unity3d.com/questions/8635/clone-a-transform-object-at-runtime.html" rel="nofollow">Unity forums</a>). The official documentation <a href="http://docs.unity3d.com/ScriptReference/Object.Instantiate.html" rel="nofollow">tells me</a> you can use Object.Instantiate to create a clone of a GameObject.

In C#, objects have always their reference passed as value, so simply reassign won't do it. See this <a href="https://stackoverflow.com/questions/4347902/when-is-a-c-sharp-value-object-copied-and-when-is-its-reference-copied?rq=1" rel="nofollow">related question</a>.

Answer3:

Objects in C# are passed by reference. If you want to copy an object, implement the ICloneable interface which has the method Clone(). You will need to copy the object yourself and return it from this method.

Recommend

  • Simple linked list-C
  • SQLite connection strategies
  • How to calculate the camera position from Vuforia GL matrix?
  • Checking if an array in C is symmetric
  • Reduction and collapse clauses in OMP have some confusing points
  • Appending Character to Character Array In C
  • OOP Javascript - Is “get property” method necessary?
  • GridView breaks while scrolling
  • copying resource to sdcard gives a damaged file in android
  • Database structure design with variable amounts of fields
  • how to adjust image in a panel in Java swing?
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Problems to linebreak with an int in JLabel
  • How reduce the height of an mschart by breaking up the y-axis
  • Possible to stop flickering java tooltip in heavyweight mode?
  • output of program is not same as passed argument
  • MySQL WHERE-condition in procedure ignored
  • How to model a transition system with SPIN
  • Rearranging Cells in UITableView Bug & Saving Changes
  • How to disable jQuery.jplayer autoplay?
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Cant find why the layout is getting smaller
  • How to stop GridView from loading again when I press back button?
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Django query for large number of relationships
  • Busy indicator not showing up in wpf window [duplicate]
  • Sorting a 2D array using the second column C++
  • costura.fody for a dll that references another dll
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?