my weapon dont get reference trough scene

hi all i have this problem. i have a shop that work with dontdestroyonload in every scene and i able to get coins trough the scene and return to the shop… the problem is that i have the object that if i buy the gun it will setactive… the problem is that the object dont get the reference in scene becouse the object rifle get destroyed in every scene… how can i reference it trough the different scene? i tried the GameObject.Find but it dont work

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class GameControlScript : MonoBehaviour {

	public Text moneyText;
	public static int moneyAmount;
	int isRifleSold;
	public static GameObject rifle;
	
	void Start () {
		moneyAmount = PlayerPrefs.GetInt ("MoneyAmount");
		isRifleSold = PlayerPrefs.GetInt ("IsRifleSold");
		rifle = GameObject.Find("BullPup");
	
		if (isRifleSold == 1)
			rifle.SetActive (true);
			
		else
			rifle.SetActive (false);
			
	}
	
	// Update is called once per frame
	void Update () {
		moneyText.text = "Money: " + moneyAmount.ToString() + "$";
		
	}

	public void gotoShop()
	{
		PlayerPrefs.SetInt ("MoneyAmount", moneyAmount);
		SceneManager.LoadScene ("Shop");
	}
}

Hello there.

Yes. As the objects (weapons) are destroyed when changing scenes, you need some kind of code in ther DontDestroyOnLoad script to Search, find, and assign again all the weapons.


A good way can be something like this. (If dont know how to do it, google it the spets you need):

First, all weapons in the game should have a Tag like “weapon” or each familiy of weapons have iots own tag “sword” “bow” …

As you know all weapons have a specyfic tag, You need to run a function everytime a new scene ha been loaded. For this you have 2 options:

Or use this: Unity - Scripting API: SceneManagement.SceneManager.sceneLoaded
Or you have a script (outside DontDestroyOnload script) that is placed in all scenes, and using the Start() function (be sure is the last script to be executed, see Unity - Manual: Script Execution Order settings)


In this function that is executed once the level has been loaded, use this function Unity - Scripting API: GameObject.FindGameObjectsWithTag to find all the objects in the scene with the tag. Once you have them, you can assign in the specyfic variable you need for yout other scripts, modify the weapons with the “upgrades” that the weapons had in the last scene, as your DontDestroyOnload script should have registred that “upgrades” as a string or int or any other class variable.

Is this what u was looking for?

Byee!