- Home /
C# Function that returns instantiated object
Hello, I need kind of help..
Here I'm trying to make a function that will return instantiated object, and put it into variable. here is the code sample;
public CLine CreateLine(Vector3 LinePos, CLine LinePrefab)
{
CLine NewLineScript;
NewLineScript = Instantiate(LinePrefab, LinePos, Quaternion.identity) as CLine;
Return (NewLineScript);
}
CLine LineScript;
LineScript = CreateLine(LinePos,LinePrefab);
The question is ,
Does the function returns instantiated object or the pointer to him?
Is the code above actually how you have it in your class? i.e. you are calling a method to return an instantiated CLine on a field?
It returns a "pointer", although it isn't called one and doesn't look like one ;-) As the others have noted, it's a reference.
Answer by Dave-Carlile · Feb 05, 2013 at 03:44 PM
In C#/.NET, any variable that "contains" an object instance in reality contains a reference to the object instance. When passing the variable around (either as a parameter, or returning it from a function) you're passing around the reference, not the object data itself.
This is completely transparent to you as a developer - it has no affect on the syntax you use to access the object. So the question is, why does this matter to you? It's rare that it should.
Well, since in C++ it is easy to distinguish pointers from regular variables, here I'm not sure whether the whole object is copied in return function or just a reference (pointer) is passed through.
Would it be any different if it would look like this?
public CLine CreateLine(Vector3 LinePos, CLine LinePrefab)
{
CLine NewLineScript;
NewLineScript = new CLine();
// Do something
Return (NewLineScript);
}
correct. c# handles pointers and memory management for you. the only time you have a duplicate variable is if you explicitly create a new variable.
assignment operators in c# pass references to objects. it's the a great beauty of c#, but could also be frustrating if you want to get into lower level memory management
As @zombience said, .NET handles everything as references - unless you specifically clone an object you're always dealing with the reference. Instantiate
creates a clone of the object, so maybe that's the question you're getting at?
Just for reference (pun intended): Note this is true for everything that's a class. However, stuff like Vector3 and Color and so on are not classes (essentially, they are "struct"s), so they will be passed by value, not as a reference. See also http://msdn.microsoft.com/en-us/library/s1ax56ch(v=vs.80).aspx
Your answer
Follow this Question
Related Questions
How can I call a function in all instances of a script 3 Answers
Distribute terrain in zones 3 Answers
C# Return Type Error? 1 Answer
Why does this prefab trigger all instances to action? C# 1 Answer
Multiple Cars not working 1 Answer