Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Struggling to get Physics.CheckSphere, Arrays and Instantiate to work together

Discussion in 'Scripting' started by VAN-D00M, Aug 18, 2014.

  1. VAN-D00M

    VAN-D00M

    Joined:
    Dec 24, 2013
    Posts:
    44
    Hi

    I'm experimenting with CheckSphere in hope that it will stop randomly instantiating my objects on top of each other as they move around. I have all my spawn points in an array which it randomly picks from. 3 objects in an array to spawn randomly. This is what I've got so far, I've taken it out of a While loop. I don't think i'm too far off if anyone could see the issue with it please. Cheers

    Code (CSharp):
    1.  
    2.  
    3. for (int i = 0; i < hazardCount; i++)
    4.             {
    5.                 Transform spawn = hazardSpawn[Random.Range(0, hazardSpawn.Length)].transform;
    6.  
    7.                 if (Physics.CheckSphere(spawn, 5))
    8.  
    9.                     Quaternion spawnRotation = Quaternion.identity;
    10.                     GameObject spawnHazard = hazard[Random.Range(0, hazard.Length)];
    11.  
    12.                     Instantiate (spawnHazard, spawn, spawnRotation);
    13.  
    14.  
    15.                     yield return new WaitForSeconds (spawnWait);
    16.             }
    17.  
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Line 7 should be
    if (Physics.CheckSphere(spawn.position, 5))
    And line 12 should also have spawn.position for the second argument
    And you need to enclose the block 8 - 12 in { }
    And since you want it to NOT spawn if there is something within the sphere, you should probably have !Physics.Checksphere
     
  3. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    For one, you should really be using a layer mask and isolating only the type of objects you are checking against. Otherwise it will probably always return true as it's likely to detect the ground or any other object in the scene.

    Two, checksphere returns true if it hits something. You are trying to not hit something.
     
  4. VAN-D00M

    VAN-D00M

    Joined:
    Dec 24, 2013
    Posts:
    44
    Oh right yeah thanks, thats only just occurred to me. Can I make the condition of the statement on whether the result is True or False? I will try that layer mask.
     
  5. RockoDyne

    RockoDyne

    Joined:
    Apr 10, 2014
    Posts:
    2,234
    hpjohn already mentions it. You use ! (typically said as 'not') to flip bool values.
     
  6. VAN-D00M

    VAN-D00M

    Joined:
    Dec 24, 2013
    Posts:
    44
    I thought so but it won't accept it. No error it just won't work.