- Home /
How to return a Vector3 value?
Hey guys, so I'm trying to figure out how the return of the void works.
I'm trying to get a vector3 from a function;
So I have, Vector3 target
in one script, an wish to assign it to the result of this long function (in another script); What I am tryin to get is the return hit.point;
at the end of the function
I was trying something like:
target = this.GetComponent<AimingSystem> ().AimForHomming ();
But it dosen't work :(
Any help much apreciated, thanks for your time
public void AimForHomming()
{
aimingforHomming = true;
y2 += Input.GetAxis ("Mouse Y") * screenSens;
if (y2 >= sH) {
y2 = sH;
}
if (y2 <= 0) {
y2 = 0;
}
x2 += Input.GetAxis ("Mouse X") * screenSens;
if (x2 >= sW) {
x2 = sW;
}
if (x2 <= 0) {
x2 = 0;
}
Vector3 screenPoint = new Vector3 (x2, y2 , 2);
Vector3 WorldPos = this.GetComponent<Attributes> ().myCam.ScreenToWorldPoint (screenPoint);
aimObj.SetActive (true);
aimObj.transform.position = WorldPos;
Ray ray = new Ray (this.GetComponent<Attributes> ().myCam.transform.position,( aimObj.transform.position - this.GetComponent<Attributes> ().myCam.transform.position));
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 1000, ~2)) {
if (hit.transform != this.GetComponent<Attributes> ().myBall) {
return hit.point;
}
}
}
Answer by Munchy2007 · May 22, 2016 at 09:02 AM
Change your function declaration to
public Vector3 AimForHomming() { ...
The use of void means that the function doesn't return anything, if you want to return something your need to replace void with the type that you want to return.
Thank you! this worked!
A side question, is it possible to change the return value of a function? Say that I hit a player,then i want to return a transform, but if I hit another object, just return a Vector3.
You can't vary the return type as such, however you could probably achieve what you want by creating a class that can act as a container for the various return types and some logic to deter$$anonymous$$e how to interpret it and have that as the return value.
Alternatively you could probably also do something using delegates.
I'd suggest you make a post in the community forum for discussion on how you might want to approach this.
Answer by NoseKills · May 22, 2016 at 09:01 AM
Read the part about return type at the end. C# Methods
Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller.
Your answer
Follow this Question
Related Questions
translate function in Js script to c# 1 Answer
Choosing function with highest return value 2 Answers
Help with function code, passing Vector3 info 1 Answer
Create a Custom Vector3 Object 2 Answers