- Home /
Using a member variable from one function in another
I've never actually needed to do this until now and I can't understand how.
I'm trying to get the hit.normal
variable from one function to use in another function within the same script.
function spawn() { //Im trying to use the hit.normal from GetPointOnMesh function var startRot = Quaternion.LookRotation(hit.normal); var fissurePrefs = Instantiate(fissure, randomPoint.point, startRot); }
function GetPointOnMesh() : RaycastHit{ var hit : RaycastHit; Physics.Raycast (ray, hit, length*2); return hit; }
Answer by Eric5h5 · Mar 14, 2011 at 06:50 PM
Variables declared inside a function are local to that function only. Since you're returning the RaycastHit from GetPointOnMesh, just call that function instead of using "hit" in your spawn function.
Its returning an error 'normal' is not a member of 'function(): UnityEngine.RaycastHit' I like this solution because it's simple, but its not see$$anonymous$$g to work. any suggestion to get around that error? Cheers
@Caius: var startRot = Quaternion.LookRotation(GetPointOn$$anonymous$$esh().normal);
Answer by kennypu · Mar 14, 2011 at 06:51 PM
this is more of a general programming question. Its a matter of scoping. Variables created within a function cannot be accessed outside of the function. So to have it be able to be accessed from outside the function, just initialize it outside the function, like so:
var hit:RaycastHit;
function spawn(){...}
function GetPointOnMesh(){...
now the problem here is, you will have to check if hit is null or not before doing your LookRotation. Hope this helps you out.
Answer by by0log1c · Mar 14, 2011 at 07:14 PM
Kennypu explained the matter of scoping, but you might want to use this approach, I did not test this specific example, but it should work:
function GetPointOnMesh():RaycastHit{ var hit : RaycastHit; Physics.Raycast (ray, hit, length*2); spawn(hit.normal); }
function spawn(thePoint){ var startRot = Quaternion.LookRotation(thePoint); var fissurePrefs = Instantiate(fissure, randomPoint.point, startRot); }
Simply send the hit.normal as a parameter to the next function.
(Note: changed the spawn function to spawnFissures) Trying to Invoke method: SpawnFissures.spawnFissures couldn't be called. Its clai$$anonymous$$g that the parameter sent is unreachable. Any ideas? Cheers for the response
Your answer
![](https://koobas.hobune.stream/wayback/20220613112813im_/https://answers.unity.com/themes/thub/images/avi.jpg)