-2
\$\begingroup\$

I created a method in my spawn manager trying to get the maximum and minimum with of spawn to be within the screen but i keep on getting the error

error CS0161: `SpawnManager.GetRandomPointOnScreen()': not all code paths return a value

does anyone have an idea as to what might be causing this error

 Vector3 GetRandomPointOnScreen()
        {

            Camera camera = Camera.main;
            float halfHeight = camera.orthographicSize;
            float halfWidth = camera.aspect * halfHeight;

            float horizontalMin = -halfWidth;
            float horizontalMax =  halfWidth;


        }
\$\endgroup\$
1

2 Answers 2

5
\$\begingroup\$

Your function declaration says it's going to return a Vector3, but you're not returning anything.

Add return Vector3(0, 0, 0); or the vector you actually want returned to the end and it will work.

\$\endgroup\$
4
\$\begingroup\$

When you start a method declaration with Vector3 SomeMethodName() you're making a promise to the compiler: "I swear, by the time you get to the end of this method, I will return an instance of the Vector3 data type!

When you don't return as promised, the compiler throws an error.

So, let's ensure we return a value:

Vector3 GetRandomPointOnScreen() { 
    Camera camera = Camera.main;
    float halfHeight = camera.orthographicSize;
    float halfWidth = camera.aspect * halfHeight; 
    float horizontalMin = -halfWidth; 
    float horizontalMax = halfWidth; 

    Vector3 randomOffset = new Vector3 (
              Random.Range(horizontalMin, horizontalMax),
              Random.Range (verticalMin, verticalMax), 
              0); 

    return randomOffset;
}

Then we can call this from inside your Spawn method from your other question, like so...

void Spawn() { 
    for (int i = 0; i < maxBalloons; i++) { 
         Vector3 randomPosition = originPosition + GetRandomPointOnScreen(); 
         Instantiate(balloon, randomPosition, Quaternion.identity);
    } 
}
\$\endgroup\$
2
  • \$\begingroup\$ can i delete the vector 2 from my spawn? \$\endgroup\$
    – Kennedy
    Commented May 25, 2018 at 2:58
  • 2
    \$\begingroup\$ I would not recommend spawning with a Vector2, because even in a 2D game z-depth & order matters. \$\endgroup\$
    – DMGregory
    Commented May 25, 2018 at 6:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .