Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Resolved Combining two objects by deleting them and instantiating the result.

Discussion in '2D' started by Endy0056, May 18, 2022.

  1. Endy0056


    Apr 16, 2022
    So, what I'm trying to accomplish is have my player hold one object, and the other sit on a counter, then when the player cursor is hovering over the counter and E is pressed, the player "places" the held object down to combine with the other one, but if Shift E is pressed, the item in combined into his inventory (inventory size one), I've got the instantiation down, but not to where the two initial items are destroyed and the resulting item is fully replacing the respecting item depending on if shift is pressed, I've only worked on the pick up combine so far, not the place until I can get the first handled.

    (This is the script on the player handling the inventory)
    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    6. public class Holding : MonoBehaviour{
    7.     public Transform Hold;
    8.     public LayerMask pick;
    9.     public GameObject itemHeld;
    10.     public GameObject Cursor;
    11.     public bool select;
    12.     public bool holding;
    13.     public Selection sel;
    14.     public GameObject box;
    15.     public Combining combine;
    16.     void Update(){
    17.         sel=box.GetComponent<Selection>();
    18.         if(Input.GetKeyDown(KeyCode.Space)){
    19.             if(itemHeld&&!sel.held&&select){
    20.                 Drop();
    21.             }else{
    22.                 Collider2D seen = Physics2D.OverlapCircle(Cursor.transform.position, .4f, pick);
    23.                 Grab(seen);
    24.             }
    25.         }
    26.     }public void Grab(Collider2D uppie){
    27.         if(uppie&&holding==false&&uppie.transform.parent!=transform){
    28.             sel.held=null;
    29.             itemHeld = uppie.gameObject;
    30.             itemHeld.transform.position = Hold.position;
    31.             itemHeld.transform.parent = transform;
    32.             holding=true;
    33.             combine=itemHeld.GetComponent<Combining>();
    34.             combine.hold=transform.GetComponent<Holding>();
    35.             itemHeld.GetComponent<SpriteRenderer>().sortingOrder = 2;
    36.             if(itemHeld.GetComponent<Rigidbody2D>())
    37.                 itemHeld.GetComponent<Rigidbody2D>().simulated = false;
    38.         }
    39.     }public void Drop(){
    40.         sel.held=itemHeld;
    41.         itemHeld.transform.position=Cursor.transform.position;
    42.         itemHeld.transform.parent = sel.transform;
    43.         holding=false;
    44.         itemHeld.GetComponent<SpriteRenderer>().sortingOrder = 0;
    45.         if(itemHeld.GetComponent<Rigidbody2D>())
    46.             itemHeld.GetComponent<Rigidbody2D>().simulated = true;
    47.         itemHeld = null;
    48.         combine.hold=null;
    49.         combine=null;
    50.     }
    51. }
    (This is the counter's script)
    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class Selection : MonoBehaviour{
    6.     public Holding hold;
    7.     public GameObject held;
    8.     public Combining combine;
    9.     public Interact act;
    10.     void Start(){
    11.         act=GetComponent<Interact>();
    12.     }private void OnTriggerEnter2D(Collider2D collider){
    13.         if(collider.tag==("Cursor")){
    14.             hold=collider.transform.parent.transform.parent.GetComponent<Holding>();
    15.   ;
    16.   ;
    17.             act.selected=true;
    18.         }
    19.     }private void OnTriggerExit2D(Collider2D collider){
    20.         if(collider.tag==("Cursor")){
    21.   ;
    22.   ;
    23.             hold=null;
    24.             act.selected=false;
    25.         }
    26.     }void Update(){
    27.         if(held){
    28.         combine=held.GetComponent<Combining>();
    29.         combine.sel=transform.GetComponent<Selection>();
    30.         }else{
    31.             combine.sel=null;
    32.             combine=null;
    33.         }
    34.         if(hold&&combine&&hold.combine){
    35.             combine.second=hold.combine;
    36.             hold.combine.second=combine;
    37.         }else{
    38.             combine.second.second=null;
    39.             combine.second=null;
    40.         }
    41.     }
    42. }
    (This is the script placed on both combined objects)
    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    6. public class Combining : MonoBehaviour
    7. {
    8.     public List<string> other;
    9.     public List<GameObject> final;
    10.     public int item;
    11.     public GameObject finalItem;
    12.     public Collider2D FinalCollider;
    13.     public Holding hold;
    14.     public Selection sel;
    15.     public Combining second;
    16.     void Update(){
    17.         if(other.Contains({
    18.             item=other.IndexOf(;
    19.         }
    20.         if(Input.GetKeyDown(KeyCode.E)){
    21.             if(Input.GetKey(KeyCode.LeftShift)){
    22.                 GrabCombine();
    23.             }else{
    24.                 PlaceCombine();
    25.             }
    26.         }
    27.     }public void GrabCombine(){
    28.         if(hold&&second){
    29.             Debug.Log(final[item];
    30.             finalItem=Instantiate(final[item], transform.position, transform.rotation);
    31.             FinalCollider=finalItem.GetComponent<Collider2D>();
    32.             hold.Grab(FinalCollider);
    33.             //Destroy(second.gameObject);
    34.             //Destroy(this.gameObject);
    35.         }
    36.     }public void PlaceCombine(){
    37.         if(sel&&second){
    39.         }
    40.     }
    41. }
    Sorry if it's too long, I'm kind of a beginner, but have some decent experience
    Last edited: May 19, 2022
  2. Kurt-Dekker


    Mar 16, 2013
    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags:

    You may edit your post above.

    Here's how to get some excellent experience analyzing your code!

    You must find a way to get the information you need in order to reason about what the problem is.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: or this answer for Android:

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:
  3. Endy0056


    Apr 16, 2022
    I can very well try to place debug logs everywhere I can, and I'll come back as soon as I can
  4. Kurt-Dekker


    Mar 16, 2013
    Definitely a good starting strategy.

    I don't want to discourage you but I want you to know what you're dealing with as far as inventories go.

    These things (character customization, inventories, shop systems) are fairly tricky hairy beasts, definitely deep in advanced coding territory. They contain elements of:

    - a database of items that you can possess / equip
    - a database of the items you actually possess / equip
    - 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
    - interaction with the world to get items in and out
    - dependence on asset definition (images, etc.) for presentation

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

    - can you have multiple items? Is there a limit?
    - 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 will they do that from a UI standpoint? What are the rules to control what can be combined and what comes out?
    - can users substantially modify items with other things like spells, gems, etc.?
    - does a worn-out item (shovel) become something else (like a stick) when the item wears out?
    - 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.

    Or... do like I like to do: just jump in and make it up as you go. It is SOFT-ware after all... evolve it as you go! :)

    Breaking down a large problem such as inventory:

    "Combining a bunch of stuff into one line always feels satisfying, but it's always a PITA to debug." - Star Manta on the Unity3D forums
  5. Endy0056


    Apr 16, 2022
    this is a yes, that is simply put as when e is pressed, the two previous are deleted while simultaneously placing the combined object down, but if Shift E is pressed, the same happens but placed in the player's hand (one slot inventory) I've kind of found a way to place the object in hand but a compiler error pops up.
    The error is: Cannot implicitly convert type 'void' to 'UnityEngine.Events.UnityEvent'
    and the code for the bit is:
    Code (csharp):
    1. public void GrabCombine(){
    2.         if(hold&&second){
    3.             Debug.Log(final[item];
    4.             finalItem=Instantiate(final[item], transform.position, transform.rotation);
    5.             FinalCollider=finalItem.GetComponent<Collider2D>();
    6.             placement=hold.Grab(FinalCollider);
    7.             placement.Invoke();
    8.             //Destroy(second.gameObject);
    9.             //Destroy(this.gameObject);
    10.         }
  6. Kurt-Dekker


    Mar 16, 2013
    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.