- Home /
Question by
landoncr4d · Jul 08, 2016 at 11:35 AM ·
randomtransform.positionrandom.rangey axisgenerating
Generating an object in a random y position? c#
I am trying to get an object to spawn in a random location on the y axis within a range. My code doesnt show up with any errors until the line "transform.position.y = randomLocation;" and that is the part which needs to be fixed. My code has not been working and I do not know why. would someone mind giving it a look? thanks in advance
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour {
public float minSpawn = 0;
public float maxSpawn = 0;
void OnCollisionEnter2D(Collision2D col){
float randomLocation = Random.Range(minSpawn,maxSpawn);
if((col.gameObject.tag == "Ball")){
transform.position.y = randomLocation;
}
}
}
Comment
To add to Hamza-Br's answer, transform.position.y cannot be directly set (same goes for x and z). It can only be accessed.
Answer by Hamza-Br · Jul 24, 2018 at 08:26 AM
You have to change the whole position so it'll be like this:
transform.position = new Vector3(transform.position.x, randomLocation, transform.position.z);