Unable to change values for objects that are not in scene in Unity

Hi all,

I know this is one of the most asked questions but I simply can’t figure it out and I’ve tried everything I could find about it.

What I’m struggling with is a pickup system. When the player picks a power up, I want to boost all of the bullets he’s using (there are different types of bullets with different stats). If I do something like this:

Projectile projectiles;

public void Start()
projectiles = GameObject.FindGameObjectWithTag("Projectile").GetComponent<Projectiles>();

I get the null reference to an object error in Unity. And I think that’s since the bullets are not necessarily in scene when the player collides with the pickup.

I don’t think that using static values would help either, since I have different values for each type of projectile.

I know it shouldn’t be that difficult, but I simply can’t figure it out… and also I’m really new to C# and Unity. I had no problems with power ups for the player for example, but I have no idea why this isn’t working.
The closest I got was using foreach but the new values would remain changed after starting the game from the beginning.

In the Projectile script I have public int damage and public float speed.

The PowerBoost script is as follows:

public class PowerBoost : MonoBehaviour
    public GameObject[] projectiles;

    public int damageBoost;
    public float speedBoost;

    private void OnTriggerEnter2D(Collider2D collision)
        if (collision.tag == "Player")
            foreach (GameObject pr in projectiles)

                        pr.GetComponent<Projectile>().speed += speedBoost;
                        pr.GetComponent<Projectile>().damage += damageBoost;

Thank you in advance!

It sounds like you are changing prefab values, as you say that the objects are not in the scene. The first script will return null, because GameObject.Find will look for objects that are in the scene. If you haven’t instantiated the prefabs yet, there are no objects to be found. In the second script, you are probably assigning the prefabs in the array in the inspector. You are then getting the scripts from those prefabs and changing the values. This is why the values remain, because you edited the prefab itself.

You could make a script where you save the values for the different projectiles and assign these values when instantiating the object. Another way, which i prefer, is to instantiate every projectile once and disable their gameobjects. They will be in the scene, but will not be visible in the game. You can then change the values on those objects. Whenever you want to instantiate a projectile, you instantiate a copy of the disabled one.