Hello, I am a Unity noob and I have had some scripting problems.
This is the file
using UnityEngine;
using System.Collections;
public class GameLoop : MonoBehaviour {
public Transform platform;
public bool notColliding = false;
public bool collided = false;
public ArrayList platforms = new ArrayList();
void Start ()
{
generatePlatforms(5);
}
void Update ()
{
}
void generatePlatforms(int range)
{
Debug.Log("CALLED");
for(int i = 0; i < 10; i++)
{
if(i == 0)
{
Debug.Log("GENERATE INITAL PLATFORM");
Transform clone;
clone = Instantiate(platform, new Vector3(0, 1, 0), Quaternion.identity) as Transform;
platforms.Add(clone);
}
else
{
Transform plat = platforms[i - 1] as Transform;
Vector3 vect = plat.position;
float pX = vect.x;
float pY = vect.y;
float pZ = vect.z;
Debug.Log("Previous Position: " + vect);
Debug.Log("Index: " + i);
while(notColliding == false)
{
float x = Random.Range(pX - range, pX + range);
float y = Random.Range(pY - range, pY + range);
float z = Random.Range(pZ - range, pZ + range);
Transform clone;
clone = Instantiate(platform, new Vector3(x, 1, z), Quaternion.identity) as Transform;
if(collided == true)
{
Destroy(clone);
Debug.Log("DESTROY");
}
else
{
platforms.Add(clone);
Debug.Log("ADDED");
collided = false;
notColliding = true;
}
}
notColliding = false;
Debug.Log("Platforms Count: " + platforms.Count);
}
}
}
}
/* Testing code
int z = 0;
for(int i = 0; i < 10; i++)
{
if(i == 0)
{
Instantiate(platform, new Vector3(0, 1, 0), Quaternion.identity);
}
else
{
z += 8;
Instantiate(platform, new Vector3(0, 1, z), Quaternion.identity);
}
}*/
The first problem is that when I run this program the generatePlatforms method is called multiple times and this is made evident by the Debug line at the top of the generatePlatforms method.
The blue line in the picture above indicates where the for is supposed to end in the code, the generatePlatforms method is called in the Start method so it should only be called once, but it is called 10 more times, does anybody know what the problem is?
The second problem is collision detection, am I going at it the right way? I am generating a new platform with random coordinates and then checking if the new platform is colliding with another platform, I put a new script into my plat prefab which is below
using UnityEngine;
using System.Collections;
public class ColliderScript : MonoBehaviour
{
GameLoop loop;
void Awake ()
{
loop = GameObject.Find("Loop").GetComponent<GameLoop>();
}
void Update () {
}
void OnCollisionEnter(Collision collision)
{
loop.collided = true;
Debug.Log("Collided!");
}
}
When I run the code with a small range (the variable which decides whether the random numbers are small or large) the chance of collision is much more likely, and the console looks like this.
Why is onCollisionEnter being called after the for loop?
Any help with both problems would be greatly appreciated thanks!