Is was building a star background simulation for a spaceshooter game in UNITY3D.
In c# i built The Instantitiation of prefabs which look like dots. While the generation of multiple dots on random spots on the x-axis go perfectly i wanted to add one thing.
Random speed. The problem is that i don't know how to give every prefab his own speed en keep it instead of getting overwritten by the next randomnization.
backgroundloop.cs
using UnityEngine;
using System.Collections;
public class backgroundloop : MonoBehaviour {
public GameObject star;
public float spawnTime;
private GameObject starPrefab;
private float timestamp;
//public float hoogte = Random.Range(-1.01f,1.1f);
//public float rotationPrefab = transform.localEulerAngles.z;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Time.time > timestamp) {
starPrefab = Instantiate
(star, new Vector3(7,Random.Range(-5.0f,5.0f),0),
Quaternion.Euler(0, 0, 0)) as GameObject;
timestamp = Time.time + spawnTime;
}
}
}
And the problem is in this script:
prefabMovement.cs
using UnityEngine;
using System.Collections;
public class prefabMovement : MonoBehaviour {
float speed = Random.Range (-3f, -0.1f);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate (new Vector3(-1f,0,0) * Time.deltaTime);
if (transform.position.x < -6.8) {
Destroy (this.gameObject);
}
}
}
Huh? So the speed is overwritten and eventually ends up being the same on all instantiated prefabs?
Maybe it helps if initialize the speed variable inside the Start method.
Related
My project is from the "Create with Unity" tutorial unit 1 with a simple vehicle moving down a road. I originally had 1 camera which worked, but when I changed the code to work with multiple cameras I couldn't get the compiler to work.
The 3 cameras are supposed to display different angles of the tank while controlling the vehicle. I assume something is wrong with how I wrote the FollowPlayer.cs "void LateUpdate()" method, but I don't know how to make it work. It all went wrong when I changedthe FollowPlayer class from 1 cam to 3 cams.
The picture shows the unity visuals and all relevant class coding is below.
I'm new to unity and c#, so any help would be appreciated!
MY CAM SWITCH CLASS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamSwitch : MonoBehaviour
{
public GameObject cam1;
public GameObject cam2;
public GameObject cam3;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Switch1"))
{
cam1.SetActive(true);
cam2.SetActive(false);
cam3.SetActive(false);
}
if (Input.GetButtonDown("Switch2"))
{
cam1.SetActive(false);
cam2.SetActive(true);
cam3.SetActive(false);
}
if (Input.GetButtonDown("Switch3"))
{
cam1.SetActive(false);
cam2.SetActive(false);
cam3.SetActive(true);
}
}
}
THE CLASS I THINK I MESSED UP
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
public Vector3 offset1= new Vector3(0, 5, -7);
public Vector3 offset2 = new Vector3(0, 3.83, -7);
public Vector3 offset3 = new Vector3(0, 7.68, -11.8);
public GameObject cam1;
public GameObject cam2;
public GameObject cam3;
cam1.SetActive(true)
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
if (cam1.SetActive(true))
{
transform.position = player.transform.position + offset1;
}
if (cam2.SetActive(true))
{
transform.position = player.transform.position + offset2;
}
if (cam3.SetActive(true))
{
transform.position = player.transform.position + offset3;
}
}
}
First: remove the line cam1.SetActive(true) under public GameObject cam3;. Its missing a semicolon and it must be placed in a function scope anyway, not in class declaration scope.
Second: this statement (and the other two) if (cam1.SetActive(true)) cant work because SetActive does not return a bool value. You probably wanted if (cam1.activeSelf).
You may spend some time improving your knowledge C# coding basics in Unity
I am making my object follow the rotation of another object. I want my object to rotate with very little difference, that is, from its current rotation it should not rotate completely with the other object.
There should be a difference u pto its rotation such that it should rotate 10% of what the main object rotates. How do I do this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowRotationWithLimit : MonoBehaviour {
public GameObject objectToFollow;
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
this.transform.eulerAngles = new Vector3 (this.transform.eulerAngles.x, objectToFollow.transform.eulerAngles.y, this.transform.eulerAngles.z);
}
}
I am not able to get that logic of creating that difference.
I would rather call it FollowRotationWithFactor then and simply use a multiplier
public class FollowRotationWithFactor : MonoBehaviour
{
public GameObject objectToFollow;
public float factor = 0.1f;
// Update is called once per frame
void Update ()
{
var eulerAngles = transform.eulerAngels;
eulerAngles.y = objectToFollow.transform.eulerAngles.y * factor;
transform.eulerAngles = eulerAngles;
}
}
I am trying to do a multiplayer game using photon and when I try to spawn objects near my player, they don't sync the same for both players. What I should add in the inspector (Already both objects that need to be spawn have PhotonView and PhotonView Transform). What I should add to my script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SpawnFix : MonoBehaviour
{
public GameObject[] powersPrefab;
public Transform[] points;
public float beat = (60 / 130) * 2;
private float timer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
[PunRPC]
void Update()
{
if (timer > beat)
{
GameObject powers = Instantiate(powersPrefab[Random.Range(0, 2)]);
powers.transform.localPosition = points[Random.Range(0, points.Length)].position;
timer -= beat;
}
timer += Time.deltaTime;
}
}
Given the similarity of your code:
Was exactly this question not already asked and answered here? (Only that there you accepted the stupid answer ^^)
Anyway
well ... that's not how [PunRPC] works. It would need to be invoked via the network somewhere e.g. via
var photonView = PhotonView.Get(this);
photonView.RPC("Update", RpcTarget.All);
HOWEVER, you definitely wouldn't want to synchronize the Update method itself every frame but rather only the spawning.
You probably should rather use PhotonNetwork.Instantiate
public class SpawnFix : MonoBehaviour
{
public GameObject[] powersPrefab;
public Transform[] points;
public float beat = (60 / 130) * 2;
private float timer;
// Update is called once per frame
void Update()
{
// only run on the master client
if(!PhotonNetwork.isMasterClient) return;
if (timer > beat)
{
PhotonNetwork.Instantiate(
powersPrefab[Random.Range(0, 2)].name,
points[Random.Range(0, points.Length)].position,
Quaternion.idendity,
0);
timer -= beat;
}
timer += Time.deltaTime;
}
}
For this the prefabs need to be registered in the Photon as spawnable objects.
Hello i want to create a group of the same prefab following the player in my game. I already got the prefab intantiation to follow the player but when there is more than one they just follow the exact same path on top of each other. is there a way where they can follow the player but act like a bunch of bees moving?
Thanks!
This is the script on my prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillerMovement : MonoBehaviour {
public GameObject player;
void FixedUpdate()
{
Vector2 toTarget = player.transform.position - transform.position;
float speed = 0.5f;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
The best solution depends on you game logic, but you may consider having a delay before starting following (you can tweak the delay depending on the position you want to the particular object to assume in the trail.
using System.Collections;
using UnityEngine;
public class Follower : MonoBehaviour
{
public GameObject player;
public float delay = 0f;
public float speed = .5f;
bool isReady = false;
void Start()
{
StartFollowing();
}
public void StartFollowing()
{
StartCoroutine(WaitThenFollow(delay));
}
IEnumerator WaitThenFollow(float delay)
{
yield return new WaitForSeconds(delay);
isReady = true;
Debug.Log(gameObject.name);
Debug.Log(Time.time);
}
void FixedUpdate()
{
if (isReady && player != null)
{
Vector2 toTarget = player.transform.position - transform.position;
transform.Translate(toTarget * speed * Time.deltaTime);
}
}
}
I've called StartFollowing in the Start method for you to test the code. You should call this method whenever approrpiate in your game logic.
In my game one normal cube change to a smaler cube.
using UnityEngine;
public class PlayerSkift : MonoBehaviour {
public GameObject myObject1;
public GameObject myObject2;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow))
{
myObject1.SetActive (false);
myObject2.SetActive (true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
myObject2.SetActive(false);
myObject1.SetActive(true);
}
}
}
This code is whats make it do so.
But when i change to my small cube, it won't go anywhere. This scrip makes the cube run.
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
Its on the smaller cube. So the smaller cube follows the bigger, this code:
using UnityEngine;
public class Pl2føglPl1 : MonoBehaviour
{
public Transform player1;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
transform.position = player1.position + offset;
}
}
when the bigger cube disappear, the little one won't start running. Pleas help if you can.
Here's what happens:
public class PlayerMovement
makes normal cube move. But public class PlayerSkift does myObject1.SetActive (false); so normal cube gets deactivated. And it doesn't get void FixedUpdate () event handler fired up anymore. So normal cube doesn't go anywhere, so smaller cube, following it, doesn't go anywhere either.
You need to create some "dummy" invisible GameObject, make your cubes children of if, attach public class PlayerMovement to it, so it always moves, regardless of inner children cubes states. And both children cubes will of course follow their parent's coordinates, since they are positioned relatively to parent. So you only move parent, and no need to synchronize cubes one to another, so you don't need public class Pl2føglPl1 at all.
This is the code i ended up using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSkiftStørelse : MonoBehaviour {
public Vector3 small;
public Vector3 normal;
public Vector3 high;
public Vector3 offset;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.DownArrow)) //getkeydown??
{
transform.localScale = small;
}
if (Input.GetKeyDown (KeyCode.UpArrow)) //getkeydown??
{
transform.localScale = normal;
}
}
}