Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved How to get a float using a string.

Discussion in 'Scripting' started by ReoCyan, Nov 11, 2023.

  1. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    I need to get float from a script. Let's say for example I have this script down here and it has a public float called MyFloat. How would I get the float from that script to another?

    Code (CSharp):
    1.  var script = GameObject.Find(GameObjectName).GetComponent(ComponentName);
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,312
    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    It isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.



    Also, avoid this nonsense:

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.
     
    ReoCyan likes this.
  3. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    I knew about the GameObject.find* one and this one was just an example but I never knew GetComponent was faulty. Do you have any sources for GetComponent alternatives because I found the part above a bit confusing?

    I'm trying to make a shop for my game and I want a script with some serialized fields I can change for each button that I can use for all/most of my shop button needs. Maybe I missed it but I'm trying to get a non static public float with a string and I couldn't find anything like it anywhere. If this does exist but there is a better way to do it, please tell me.

    Goal:
    Code (CSharp):
    1.  
    2. Value = Script.FindValue(StringValueName);
    3. If(Requirements met)
    4. {
    5.  
    6. }
    7.  
    Also, if it means anything to you, thanks for posting onto these forums. I have been quietly watching your posts and found them very insightful. Many times when looking onto your forums, your answers helped me when I couldn't find anything I could understand on any other documentation source or Youtube video after long hours of searching and failing.

    *Is it okay to use tags because that's what I use for my code.
     
  4. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    Sorry, I posted that by accident. I wasn't finished with the code and was just outlining the example. I just want to find a value using a method like the above or something better.
     
  5. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,740
  6. patrick_Drake

    patrick_Drake

    Joined:
    Jul 2, 2023
    Posts:
    18
    Do you just want to get the float from a different script or do you want to get it by passing an actual string to it? For the first get a reference to the gameibject that has the script on it, then call
    Code (CSharp):
    1. Float f = gameobjectwithscriptonit.GetComponent<scriptname>().floatname;
    For the second you could put the float in a dictionary with a string as it's key and then access the dictionary in the same way as above but with the dictionary name at the end with the string as it's [key].
     
  7. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    I can't type in the float name. I need to do this:

    Code (CSharp):
    1. [SerializeField] string FloatName
    2. var float Value =  Script.GetValue(FloatName)
    This is because I have multiple of these scripts and I need to get a specific value for each one using strings or a better method that still has the versatility.
     
  8. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    Obviously this isn't a real function because I don't know how to get the value but this is generally what I want to do.
     
  9. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,740
    I highly recommend you don't do this but here's how you would do it. Be aware it's bypassing the rules that make debugging far less painful, is very much error prone, is slower due to reflection having to reference meta data on the class, and is only supported on some platforms.
    Code (csharp):
    1. using System.Reflection;
    2.  
    3. var instance = GameObject.Find(GameObjectName).GetComponent<MyScriptClass>();
    4. var value = typeof(MyScriptClass).GetField("FloatName", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(instance);
    Ideally you write scripts that don't need to change the field name they reference on the fly.
    Code (csharp):
    1. var value = GameObject.Find(GameObjectName).GetComponent<MyScriptClass>().FloatName;
     
    Last edited: Nov 12, 2023
    ReoCyan likes this.
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,312
    Just so you know what you're getting into here...

    These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.

    Inventory code never lives "all by itself." All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.

    Inventories / shop systems / character selectors all contain elements of:

    - a database of items that you may possibly possess / equip
    - a database of the items that you actually possess / equip currently
    - perhaps another database of your "storage" area at home base?
    - persistence of this information to storage between game runs
    - presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
    - interaction with items in the inventory or on the character or in the home base storage area
    - interaction with the world to get items in and out
    - dependence on asset definition (images, etc.) for presentation

    Just the design choices of such a system can have a lot of complicating confounding issues, such as:

    - can you have multiple items? Is there a limit?
    - if there is an item limit, what is it? Total count? Weight? Size? Something else?
    - are those items shown individually or do they stack?
    - are coins / gems stacked but other stuff isn't stacked?
    - do items have detailed data shown (durability, rarity, damage, etc.)?
    - can users combine items to make new items? How? Limits? Results? Messages of success/failure?
    - can users substantially modify items with other things like spells, gems, sockets, etc.?
    - does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
    - etc.

    Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.

    Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.

    Breaking down a large problem such as inventory:

    https://forum.unity.com/threads/weapon-inventory-and-how-to-script-weapons.1046236/#post-6769558

    If you want to see most of the steps involved, make a "micro inventory" in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).

    Everything you learn doing that "micro inventory" of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.

    Breaking down large problems in general:

    https://forum.unity.com/threads/opt...n-an-asteroid-belt-game.1395319/#post-8781697

    The moment you put an inventory system into place is also a fantastic time to consider your data lifetime and persistence. Create a load/save game and put the inventory data store into that load/save data area and begin loading/saving the game state every time you run / stop the game. Doing this early in the development cycle will make things much easier later on.
     
    ReoCyan likes this.
  11. ReoCyan

    ReoCyan

    Joined:
    Sep 25, 2023
    Posts:
    34
    Tell me if I'm wrong but I don't think I need a very complex inventory and shop with my game. Here's the list of things I want:

    A. Stat Changes: I already have these in my game but I'd rather make a more efficient system for them. Thus the reference question.

    B. Seeds: There is no limit to how much seed types you can have but there is a limit to the amount of a type of seed you can get. Some specialties of seeds would be that some plants give off the seed type it was or sometimes the player needs to buy access to buy the seeds.

    C. Materials: Same circumstance with the seeds except in some cases there's no limit to the amount. Players can get certain materials by collecting them and/or by buying them.

    Tell me if I'm wrong but I only need a way to hide the inventory and show the amounts of stuff the player. I'd rather not show stat changes in the inventory. I think I should put it in the shop. I don't want the inventory to slow the player down because there's enemies that try to defeat players while they farm.
     
  12. flashframe

    flashframe

    Joined:
    Feb 10, 2015
    Posts:
    773
    You could use an interface to share functionality amongst your classes.

    If you are trying to access a float value from multiple classes and perform a similar operation on it, but you want to name the variables differently, then instead of directly accessing the variables by name, you could define a method or a property that gets/sets the float value.