Search Unity

Cannonball (SOLVED)

Discussion in 'Scripting' started by MiguelMNavas, Jun 26, 2019.

  1. MiguelMNavas

    MiguelMNavas

    Joined:
    May 27, 2019
    Posts:
    2
    Hi to everyone:

    Recently I am doing an online course and suppousely I should follow some steps to achieve that a turret shoots cannonballs. The thing is I wrote the same script which appears in the video, but any cannonball is coming. Could someone help me to see where is the error?

    Here I post the script:

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

    public class Turret : MonoBehaviour {

    public Transform player = null;
    public GameObject cannonball = null;

    public float minDelay = 1.0f;
    public float maxDelay = 4.0f;

    private float lastTime = 0.0f;
    private float delayTime = 0.0f;


    private void Update()
    {
    FollowPlayer();
    }

    void FollowPlayer ()
    {
    this.transform.LookAt(player);
    }

    void Shoot()
    {
    if (Time.time > lastTime + delayTime )
    {
    lastTime = Time.time;
    delayTime = GetRandomValue();

    GameObject obj = Instantiate(cannonball, this.transform.position, this.transform.rotation) as GameObject;

    obj.name = "cannonball";
    }
    }

    float GetRandomValue ()
    {
    return Random.Range(minDelay, maxDelay);
    }


    }
     
  2. MiguelMNavas

    MiguelMNavas

    Joined:
    May 27, 2019
    Posts:
    2
    private void Update()
    {
    FollowPlayer();

    Shoot ();

    }
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,738
    Glad you solved it! Next time please check the code formatting guidelines in the very first forum post to help us understand your code better.