Why when adding a script to a selected gameobject through another script it's adding the script to each object in the list twice? - c#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class GenerateAutomaticGuid : Editor
{
[MenuItem("GameObject/Generate Guid", false, 11)]
private static void GenerateGuid()
{
foreach (GameObject o in Selection.objects)
{
o.AddComponent<GenerateGuid>();
o.GetComponent<GenerateGuid>().GenerateGuidNum();
o.tag = "My Unique ID";
}
}
}
For example I'm selecting two gameobjects in the hierarchy right click and GenerateGuid I use a break point and it's making a loop on each object in the list Selection.objects twice so each object in the list have the script GenerateGuid twice. And I want it to add the script to each object once only.
This is the GenerateGuid script :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateGuid : MonoBehaviour, IStateQuery
{
public string uniqueGuidID;
public SaveLoad saveLoad;
public GameObject naviParent;
private Guid guidID;
private bool isNaviChildOfKid = false;
public void GenerateGuidNum()
{
guidID = Guid.NewGuid();
uniqueGuidID = guidID.ToString();
}
private State m_state = new State();
public Guid UniqueId => Guid.Parse("E0B03C9C-9680-4E02-B06B-E227831CB33F");
private class State
{
public bool naviInHand;
}
public string GetState()
{
return JsonUtility.ToJson(m_state);
}
public void SetState(string jsonString)
{
m_state = JsonUtility.FromJson<State>(jsonString);
if (m_state.naviInHand == true)
{
transform.GetComponent<InteractableItem>().distance = 0;
transform.parent = GameObject.Find("Navi Parent").transform;//rig_f_middle;
transform.localPosition = GameObject.Find("Navi Parent").transform.localPosition;
transform.localRotation = Quaternion.identity;
transform.localScale = new Vector3(0.001f, 0.001f, 0.001f);
}
}
private void Update()
{
if(transform.IsChildOf(naviParent.transform) == false && isNaviChildOfKid == false)
{
m_state.naviInHand = true;
saveLoad.Save();
isNaviChildOfKid = true;
}
}
}
A screenshot of all the places I'm calling the GenerateGuid :

Maybe you executing GenerateGuid twice or by amount of gameobjects?
Can you show all places where you executing GenerateGuid

You can add a null check to your foreach loop to see if your object already has a GenerateGuid component and skip the process if it does:
foreach (GameObject o in Selection.objects)
{
if(!o.GetComponent<GenerateGuid>()){
o.AddComponent<GenerateGuid>();
o.GetComponent<GenerateGuid>().GenerateGuidNum();
o.tag = "My Unique ID";
}
}
It won't prevent your function from being called multiple times but it can prevent duplicate GenerateGuid components.

Related

GetKeyDown sends multiple outputs

specifically it sends as many outputs as there are objects with the code in them that allows them to be interacted with, even if I press E when not looking at anything. I wanted to make an inventory system, but this causes all objects that have this code to be interacted with. I included all the scripts that im using for this system if that can help. I genuinely don't know what I did wrong
the interactor code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
public class Interactable : MonoBehaviour
{
public LayerMask interactableLayerMask;
//ITEM VARIABLE
public Item item;
//PICK UP RADIUS
public float radius = 4f;
public void Interact()
{
Debug.Log("Interacted with " + transform.name);
PickUp();
}
//PICK UP INTERACTION
void PickUp()
{
Debug.Log("Picking up " + item.name);
bool wasPickedUp = Inventory.instance.Add(item);
if (wasPickedUp)
Destroy(gameObject);
}
//INTERACTION
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("Added item -----------------------------------------");
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, radius))
{
Interactable interactable = hit.collider.GetComponent<Interactable>();
if (interactable != null)
{
Interact();
}
} else
{
Debug.Log("Nothing");
}
}
}
}
the Inventory code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
#region Singleton
public static Inventory instance;
void Awake()
{
if (instance != null)
{
Debug.LogWarning("More than one instance of Inventory found!");
return;
}
instance = this;
}
#endregion
public delegate void OnItemChanged();
public OnItemChanged onItemChangedCallback;
public int space = 20;
public List<Item> items = new List<Item>();
public bool Add (Item item)
{
if (!item.isDefaultItem)
{
if (items.Count >= space)
{
Debug.Log("Note enough space in inventory");
return false;
}
else
{
items.Add(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
}
}
return true;
}
public void Remove(Item item)
{
items.Remove(item);
if (onItemChangedCallback != null)
onItemChangedCallback.Invoke();
}
}
Item code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
public class Item : ScriptableObject
{
new public string name = "New Item";
public Sprite icon = null;
public bool isDefaultItem = false;
}
To my understanding, your code goes into the Input.GetKeyDown(KeyCode.E) for every object in the scene, but it does not add it to the inventory.
That is because you use the Update function in the Interactable class, which are your objects. Instead, try moving the exact same block of code into your Inventory class. Make sure you make your Interact method public, so you can call it.

How can I init a list according to the game state if the game is running or not?

I have this monobehaviour script :
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
public class CompareObjects : MonoBehaviour
{
public GameObject mainGame;
public string comparisonObjects;
public float waitTime;
public List<GameObject> allobjects = new List<GameObject>();
public bool startComparingAtStart = false;
private Coroutine comparer;
private void Start()
{
if (Application.isPlaying == false)
{
allobjects = new List<GameObject>();
}
else
{
allobjects = FindObjectsOfType<GameObject>().ToList();
}
if (startComparingAtStart == true)
{
StartComparing();
}
}
public void StartComparing()
{
mainGame.SetActive(false);
if (comparer == null)
{
comparer = StartCoroutine(Compare());
}
}
public void StopComparing()
{
if (comparer != null)
{
comparisonObjects = "";
allobjects = new List<GameObject>();
StopCoroutine(comparer);
mainGame.SetActive(true);
comparer = null;
}
}
IEnumerator Compare()
{
while (true)
{
foreach (GameObject go in allobjects)
{
if (go.name != "Game Manager")
{
comparisonObjects = go.name + " >>>>> " + go.scene.name + " >>>>> is active object";
}
yield return new WaitForSeconds(waitTime);
}
}
}
}
And editor script for buttons in inspector :
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(CompareObjects))]
public class CompareObjectsButton : Editor
{
private CompareObjects compareObjects;
private void OnEnable()
{
compareObjects = (CompareObjects)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
CompareObjects myTarget = (CompareObjects)target;
if (GUILayout.Button("Compare Objects"))
{
myTarget.StartComparing();
}
if (GUILayout.Button("Stop"))
{
myTarget.StopComparing();
}
}
}
This part is not working :
if (Application.isPlaying == false)
{
allobjects = new List<GameObject>();
}
else
{
allobjects = FindObjectsOfType<GameObject>().ToList();
}
When running the game and clicking the start Compare Objects button if I will click the Stop button it will reset the List allObjects to length 0.
But if instead clicking the Stop button I just strop the game the allObjects list will be empty but the length will keep be over 5000 items. It's the items will be empty but I want that when the game is not running the list to be length 0.
Not sure why it keep the list length over 5000 items and how to reset it to length 0.
Tried to use the :
Application.isPlaying
But it's not working.
This is what I tried so far :
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[ExecuteAlways]
public class CompareObjects : MonoBehaviour
{
public GameObject mainGame;
public string comparisonObjects;
public float waitTime;
public List<GameObject> allobjects = new List<GameObject>();
public bool startComparingAtStart = false;
private Coroutine comparer;
private void Start()
{
if (Application.isPlaying == false)
{
allobjects = new List<GameObject>();
}
else
{
allobjects = FindObjectsOfType<GameObject>().ToList();
}
if (startComparingAtStart == true)
{
StartComparing();
}
}
public void StartComparing()
{
mainGame.SetActive(false);
if (comparer == null)
{
comparer = StartCoroutine(Compare());
}
}
public void StopComparing()
{
if (comparer != null)
{
comparisonObjects = "";
allobjects = new List<GameObject>();
StopCoroutine(comparer);
mainGame.SetActive(true);
comparer = null;
}
}
IEnumerator Compare()
{
while (true)
{
foreach (GameObject go in allobjects)
{
if (go.name != "Game Manager")
{
comparisonObjects = go.name + " >>>>> " + go.scene.name + " >>>>> is active object";
}
yield return new WaitForSeconds(waitTime);
}
}
}
}
But if the comparing is working the Coroutine is in the middle and I quit the game pressing the play button to quit the game the whole editor is freezing and I need to force close it in the Task Manager.
Code if (Application.isPlaying == false) not working in your case because it places in MonoBehaviour's Start method which called only in playmode by default.
To make code workable you can move allobjects initialization to StartComparing/StopComparing methods or play with ExecuteInEditMode or ExecuteAlways attributes to run code in editor mode.

Unity Quiz Game Score in C#

I am making a quiz game in the unity from the unity live session quiz game tutorials everything is working fine except somehow the score isn't working when i Click the button it should add 10 score to the Score. Here are the tutorials : https://unity3d.com/learn/tutorials/topics/scripting/intro-and-setup?playlist=17117 and the code for my Game Controller :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class GameController : MonoBehaviour {
public Text questionDisplayText;
public Text scoreDisplayText;
public Text timeRemainingDisplayText;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
public GameObject questionDisplay;
public GameObject roundEndDisplay;
private DataController dataController;
private RoundData currentRoundData;
private QuestionData[] questionPool;
private bool isRoundActive;
private float timeRemaining;
private int questionIndex;
private int playerScore;
private List<GameObject> answerButtonGameObjects = new List<GameObject>();
// Use this for initialization
void Start ()
{
dataController = FindObjectOfType<DataController> ();
currentRoundData = dataController.GetCurrentRoundData ();
questionPool = currentRoundData.questions;
timeRemaining = currentRoundData.timeLimitInSeconds;
UpdateTimeRemainingDisplay();
playerScore = 0;
questionIndex = 0;
ShowQuestion ();
isRoundActive = true;
}
private void ShowQuestion()
{
RemoveAnswerButtons ();
QuestionData questionData = questionPool [questionIndex];
questionDisplayText.text = questionData.questionText;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
answerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
public void AnswerButtonClicked(bool isCorrect)
{
if (isCorrect)
{
playerScore += currentRoundData.pointsAddedForCorrectAnswer;
scoreDisplayText.text = "Score: " + playerScore.ToString();
}
if (questionPool.Length > questionIndex + 1) {
questionIndex++;
ShowQuestion ();
} else
{
EndRound();
}
}
public void EndRound()
{
isRoundActive = false;
questionDisplay.SetActive (false);
roundEndDisplay.SetActive (true);
}
public void ReturnToMenu()
{
SceneManager.LoadScene ("MenuScreen");
}
private void UpdateTimeRemainingDisplay()
{
timeRemainingDisplayText.text = "Time: " + Mathf.Round (timeRemaining).ToString ();
}
// Update is called once per frame
void Update ()
{
if (isRoundActive)
{
timeRemaining -= Time.deltaTime;
UpdateTimeRemainingDisplay();
if (timeRemaining <= 0f)
{
EndRound();
}
}
}
}
and my answer Button Code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AnswerButton : MonoBehaviour {
public Text answerText;
private AnswerData answerData;
private GameController GameController;
// Use this for initialization
void Start ()
{
GameController = FindObjectOfType<GameController> ();
}
public void Setup(AnswerData data)
{
answerData = data;
answerText.text = answerData.answerText;
}
public void HandleClick()
{
GameController.AnswerButtonClicked (answerData.isCorrect);
}
}
and Answer Data :
using UnityEngine;
using System.Collections;
[System.Serializable]
public class AnswerData
{
public string answerText;
public bool isCorrect;
}
If everything is working fine (the whole code gets executed correctly, which I presume at this point), you probably did not set the data correctly. In your Game Controller, you have the line
playerScore += currentRoundData.pointsAddedForCorrectAnswer;
in your AnswerButtonClicked method which should add an amount you defined to the score if the answer is correct. Since I presume that your whole code is running fine (I can't see your in-engine setup, only the code here, which looks like the one in the tutorial), this is probably the first location where to look at the error. This value is probably set in the Unity Inspector or via another script, so you may want to go check in other files or the Editor.
The next thing to check is, if the buttons are correctly linked via their event handler. This can be checked by looking at the inspector. In the tutorial series this step is done in part Click to answer at the end of the video.

Get value from other script file variable Unity C#

I have a weird question. I want to get value from other script file, but actually it is quick easy. But this time I have an another case.
For example:
I have player.cs that save the data with datatype dictionary
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class player : MonoBehaviour {
public Dictionary <string, Dictionary <string, int> > product;
}
then I have margaretShop.cs that set the value of dictionary product
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
public class margaretShop : MonoBehaviour {
player Player;
// Use this for initialization
void Start () {
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player> ();
setValue("A", "id", "10");
setValue("A", "name", "A");
setValue("A", "qty", "4");
setValue("A", "price", "120");
}
// Update is called once per frame
void Update () {
}
void init() {
if (Player.product != null) {
return;
}
Player.product = new Dictionary<string, Dictionary <string, int> > ();
}
public int getValue(string nameproduct, string property) {
init ();
if (Player.product.ContainsKey (nameproduct) == false) {
return 0;
}
if (Player.product [nameproduct].ContainsKey (property) == false) {
return 0;
}
return Player.product [nameproduct] [property];
}
public void setValue(string nameproduct, string property, int value) {
init ();
if (Player.product.ContainsKey (nameproduct) == false) {
Player.product[nameproduct] = new Dictionary<string, int>();
}
Player.product [nameproduct] [property] = value; // This store to player.cs file product
}
public string[] getProductName() {
return Player.product.Keys.ToArray();
}
}
and then last I call it with another script file margaretSellScript.cs
using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEngine.UI;
public class margaretSellScript : MonoBehaviour {
margaretShop mShop;
player Player;
// Use this for initialization
void Start () {
mShop = GameObject.FindGameObjectWithTag ("MargaretShop").GetComponent<margaretShop> ();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player> ();
Debug.Log("QTY : " + mShop.getValue ("A", "qty"));
}
}
In this script: Debug.Log("QTY : " + mShop.getValue ("A", "qty")); why I can't get the value from player.cs product variable dictionary? The value must be "4" right?
The error is Object reference not set to an instance of an object
I have already call the gameobject like this at margaretSellScript.cs :
mShop = GameObject.FindGameObjectWithTag ("MargaretShop").GetComponent<margaretShop> ();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player> ();
Any Idea?
But i see it is attacted. Just i am not set it active until i press
the button.
That's the problem. The component must be enabled in order for GetComponent<Script> () to find it. Enable it from the Editor as default. When game starts get the reference then disable it.
mShop = GameObject.FindGameObjectWithTag("MargaretShop").GetComponent<margaretShop>();
mShop.enabled = false; //disable it
If you have any code that runs in the Start() function of the margaretShop script, you can remove them and put them in a custom public function named initScript().
Now, when you press the Button, you can activate it with mShop.enabled = false;, then call the initScript() function to initialize your variables in the margaretShop script. That's it.

Unity C# Problems

I am getting this error:
An object reference is required to access non-static member
`Inventory.ItemID'
I want to change ItemID in Inventory to 1.
The class ItemSwordUneq:
using UnityEngine;
using System.Collections;
public class ItemSwordUneq : MonoBehaviour
{
public bool canPickup = false;
void Update ()
{
if(canPickup == true && Input.GetKeyDown(KeyCode.F))
{
GameObject player = GameObject.Find("Player");
Inventory inventory = player.GetComponent<Inventory>();
Inventory.ItemID = 1;
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider other)
{
canPickup = true;
}
void OnTriggerExit(Collider other)
{
canPickup = false;
}
void OnGUI()
{
if(canPickup == true)
{
GUI.Label(new Rect(250, 250, 300, 20), "Press 'F' To Pick Up Sword");
}
}
}
The class Inventory:
using UnityEngine;
using System.Collections;
public class Inventory : MonoBehaviour
{
public bool hasItem = false;
public int ItemID;
}
What am I doing wrong? Any answers will be appreciated.
You probably want to write inventory.ItemID = 1; instead of Inventory.ItemID = 1;.
That is if you want to set the ItemId of the result of player.GetComponent<Inventory>(); to 1.
You are trying to call a method on the class Inventory and not on the object inventory, and that does not give any sense if the method is not static.

Categories