0
\$\begingroup\$

I'm making a simple shooter game where the player shoots a projectile at objects that spawn in random locations. I'd like to change the speed of the spawned objects and am having two issues

  1. not sure how to call the speed from a separate script. I'm guessing I need to use GetComponent and could use some advice.
  2. how do i vary the speed of spawned enemy objects? Ideally it'd be random from a range of 5 to 20

Move Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveForward : MonoBehaviour
{
  public float speed = 20f;
  public GameObject Trump;
  public GameObject Player;
  private Rigidbody enemyRb;
  // Start is called before the first frame update
  void Start()
  {
    enemyRb = GetComponent<Rigidbody>();
    Player = GameObject.Find("Player");
    this.transform.LookAt(Player.transform);


  }

  // Update is called once per frame
  void Update()
  {
    transform.Translate(Vector3.forward * Time.deltaTime * speed);
   
    
  }
}

Spawn Manager Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
  public GameObject Trump;
  private float spawnRange = 60;
  private float startDelay = 2;
  private float spawnInterval = 1.5f;

  // Start is called before the first frame update
  void Start()
  {
    InvokeRepeating("SpawnTrump", startDelay, spawnInterval);

  }

  // Update is called once per frame
  void Update()
  {
   // MoveForward.speed += speedIncreasePerSpawn * spawnCount;
    //spawnCount++;
  }

  void SpawnTrump()
  {
    Instantiate(Trump, GenerateSpawnPosition(), Trump.transform.rotation);
  }
  private Vector3 GenerateSpawnPosition()
  {
    float spawnPosX = Random.Range(-spawnRange, spawnRange);
    float spawnPosZ = Random.Range(-spawnRange, spawnRange);
    Vector3 randomPos = new Vector3(spawnPosX, 0, spawnPosZ);
    return randomPos;

  }
}
\$\endgroup\$
0
\$\begingroup\$

Did you mean to write something like this?

public MoveForward prefabToSpawn; 
public float minSpeed = 5f;
public float maxSpeed = 20f;

void Spawn()
{
    MoveForward spawned = Instantiate(
                                  prefabToSpawn,
                                  GenerateSpawnPosition(), 
                                  prefabToSpawn.transform.rotation);

    spawned.speed = Random.Range(minSpeed, maxSpeed);
}

This is a fairly trivial application of methods you can find in the Unity documentation and in beginner guides, so you may want to work through some more tutorials to make sure you've got a good grasp of the basics.

\$\endgroup\$
1
  • \$\begingroup\$ working on it. thank you \$\endgroup\$ – jenkatan29 Jun 28 '20 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.