Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Using a local ref [Object] variable? Any ideas for elegant solution?

Discussion in 'Scripting' started by vampir26, Nov 12, 2018.

  1. vampir26

    vampir26

    Joined:
    Mar 29, 2010
    Posts:
    108
    Hi

    I have lots of buildable structures and every structure have a ui window.

    Example: The player can build an animal trap. If he open the trap (ui window), he can add a bait into a slot.

    My problem is:
    1. The item (bait) is assigned to the ui and the ui will be destroyed, if the player close the window.
    2. The main code is into the main script (AnimalTrap.cs), but it also need access to the item, while the ui window is open. Both scripts need access to the same Object (Item) at the same time. I tried it with ref, but it won't work (not available in .net V4.0).

    This script (shorten) will show you my problem:

    Code (CSharp):
    1.  
    2. AnimalTrap.cs:
    3. --------------------
    4. Item baitItem = null;
    5. void Update() {
    6. if(Input.GetKey(KeyCode.E))
    7.    CreateAndOpenWindow(baitItem);
    8. }
    9. //here is the logic, this script is working with baitItem
    10. //this script must do the work, don't matter if window is open or close
    11.  
    12. WndAnimalTrap.cs
    13. --------------------
    14. void CreateAndOpenWindow(ref Item baitItem){
    15.    (SlotScript)baitSlot.Initialize(baitItem);
    16. }
    17.  
    18. SlotScript.cs (drag & drop items on this slot, used for every structure)
    19. --------------------
    20. ref Item item = null;
    21. Initialize(ref Item item){
    22. this.item = item;
    23. }
    24. //this script is an item slot and the player add items to it (OnPointerDown)
    25.  
    Hope you understand me, it's a bit difficult to describe.

    Do you know an elegant solution?