Similar question to before, but a bit clearer I hope. Currently I have one projectile that can be fired in my scene when I press button down. I have another physical projectile in my scene, which is positioned next to it. I want to be able to fire it also using button down after I fire the first projectile. I Dont want to instantiate or anything like that. Here is the code I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rocket : MonoBehaviour
{
public float force = 50f;
private Rigidbody rb;
public bool IsLaunched;
public float fakeGravity = 5f;
public Transform tip;
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
if (IsLaunched)
{
rb.AddForce(transform.up * force);
rb.AddForceAtPosition(Vector3.down * fakeGravity, tip.position);
}
}
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
IsLaunched = true;
rb.useGravity = true;
}
}
}
If you have an array of rigidbodies, you can fire off the next rigidbody in the array when Fire1 is pressed:
public Rigidbody[] rbs;
int Index = 0;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
IsLaunched = true;
rbs[Index].useGravity = true;
Index++;
}
}
@gamedevunity12
Note: This answer comes largely as a response to the existing answer and comments.
By having the set of objects tracked together, another approach to take would be to have a separate controller to launch the rockets instead. For example:
// Not complete, but intended to include important details
public class RocketLauncher : MonoBehaviour
{
// Use this to add an indeterminate
// quantity of rockets and to easily cycle through them
public List<Rocket> rockets;
// Or, alternatively, use this with a fixed
// set of rockets
public Rocket[] rockets;
int lastRocketFired = 0;
void Update()
{
if(Input.GetButtonDown("Fire1") && rockets.Count > 0) // List
//if(... && lastRocketFired < rockets.Length) // Array
{
// Fire first rocket and remove from the list so the next
// in line will be the new first entry
rockets[0].Launch();
rockets.RemoveAt(0);
// For an array, keep track of which you last launched
// instead, then fire the next in sequence
rockets[lastRocketFired].Launch();
lastRocketFired++; // Add 1
}
}
}
// Example of rockets adding themselves to the launcher
public class Rocket : MonoBehaviour
{
private static RocketLauncher launcher;
// Start function will add itself to the launcher
// However, it may not have strict control over the order
// if multiple rockets will be added at the same time (i.e. game start)
void Start()
{
if(launcher == null) // More efficient than reusing FindObject
{
launcher = (RocketLauncher)FindObjectOfType(typeof(RocketLauncher));
}
// Adding itself to List<> variant
launcher.rockets.Add(this);
}
public void Launch()
{
isLaunched = true;
rb.useGravity = true;
}
}