Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question gameobject with on screen button, new input syste and same script affecting each other

Discussion in 'Scripting' started by unity_6103548EB384C2C58CE0, Sep 16, 2023.

  1. unity_6103548EB384C2C58CE0

    unity_6103548EB384C2C58CE0

    Joined:
    Feb 3, 2023
    Posts:
    3
    So im making a tower defense game for mobile , and i made 2 gameObject for selecting a tower. the problem is, that when i added the 2nd gameobject with the samescript the script for selecting a tower and placing them is not right anymore. the tower that is for tower 1 is the prefab that is getting instantiated for the tower 2. but when its just 1 its working fine. im new in unity and dont know the best approach to making this. this is my script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem;
    5. using Cinemachine;
    6.  
    7. public class TowerPlacement : MonoBehaviour
    8. {
    9.     //References
    10.     PlayerInput playerInput;
    11.     private InputAction _touchPressedAction;
    12.     private InputAction _touchPlacePressAction;
    13.     private InputAction _touchPressAction;
    14.  
    15.     public GameObject[] _meleePlatform;
    16.     CanvasEnabler canvasEnabler;
    17.     //
    18.     [Space(5)]
    19.     [Header("Canvas")]
    20.     [SerializeField] GameObject _CharConfirmPlacementCanvas;
    21.     [SerializeField] GameObject _charInfoCanvas;
    22.     [SerializeField] string _platformTag;
    23.  
    24.     float placingGameTimeSpeed = 0.1f;
    25.     float normalGameTimeSpeed = 1f;
    26.  
    27.     Ray _position;
    28.     [Space(5)]
    29.     [Header("Character Object")]
    30.     [SerializeField] private GameObject _previewTower;
    31.     [SerializeField] private GameObject _tower;
    32.     [Space(5)]
    33.     [Header("Camera")]
    34.     [SerializeField] private Camera _mainCam;
    35.  
    36.     [Header("Object Material")]
    37.     [SerializeField] Material[] _materia;
    38.  
    39.     [Space(5)]
    40.     [Header("Raycast")]
    41.     [SerializeField] LayerMask _layerPlatform;
    42.     float maxDistance;
    43.  
    44.     [SerializeField] CinemachineVirtualCamera vcam1;
    45.     [SerializeField] CinemachineVirtualCamera vcam2;
    46.  
    47.     bool rayCastHit;
    48.  
    49.     Renderer rend;
    50.  
    51.     bool _isPlacing;
    52.  
    53.     // Material mat;
    54.  
    55.     private GameObject _instPreviewObj;
    56.     private GameObject _instObj;
    57.  
    58.     public enum State
    59.     {
    60.         Default,
    61.         Placing,
    62.         HoldPlacing,
    63.         Placed
    64.     }
    65.  
    66.     private State currentState;
    67.  
    68.  
    69.     private void Awake()
    70.     {
    71.         playerInput = GetComponent<PlayerInput>();
    72.         _touchPressedAction = playerInput.actions["Pressed"];
    73.         _touchPressAction = playerInput.actions["Press"];
    74.         _touchPlacePressAction = playerInput.actions["PlacePress"];
    75.         currentState = State.Default;
    76.  
    77.         _meleePlatform = GameObject.FindGameObjectsWithTag(_platformTag);
    78.  
    79.     }
    80.  
    81.     private void Update()
    82.     {
    83.  
    84.         switch (currentState)
    85.         {
    86.             case State.Default:
    87.  
    88.  
    89.                 Time.timeScale = normalGameTimeSpeed;
    90.                 vcam1.Priority = 1;
    91.                 vcam2.Priority = 0;
    92.                 Debug.Log(currentState);
    93.                 _charInfoCanvas.SetActive(false);
    94.                 DisablePlatformCanvas();
    95.                 break;
    96.             case State.Placing:
    97.                 Time.timeScale = placingGameTimeSpeed;
    98.                 EnablePlatformCanvas();
    99.                 //TODO:: Move the camera a bit when palcing
    100.                 vcam1.Priority = 0;
    101.                 vcam2.Priority = 1;
    102.                 Debug.Log(currentState);
    103.                 _charInfoCanvas.SetActive(true);
    104.                 break;
    105.             case State.HoldPlacing:
    106.                 Debug.Log(currentState);
    107.                 _CharConfirmPlacementCanvas.SetActive(true);
    108.                 _CharConfirmPlacementCanvas.transform.position = _instPreviewObj.transform.position;
    109.  
    110.                 break;
    111.             case State.Placed:
    112.                 Debug.Log(currentState);
    113.  
    114.                 break;
    115.         }
    116.  
    117.     }
    118.  
    119.     private void OnEnable()
    120.     {
    121.         _touchPressAction.performed += OnPressed;
    122.  
    123.  
    124.     }
    125.     private void OnDisable()
    126.     {
    127.         _touchPressedAction.started -= OnPlacing;
    128.         _touchPressedAction.canceled -= Hold;
    129.         _touchPlacePressAction.canceled -= OnPressed;
    130.     }
    131.  
    132.     public void OnPressed(InputAction.CallbackContext context)
    133.     {
    134.         if (_isPlacing)
    135.         {
    136.             _isPlacing = false;
    137.             Destroy(_instPreviewObj);
    138.             _CharConfirmPlacementCanvas.SetActive(false);
    139.             currentState = State.Default;
    140.             return;
    141.         }
    142.         if (currentState == State.Default)
    143.         {
    144.             Debug.Log("Press");
    145.             _instPreviewObj = Instantiate(_previewTower, transform.position, Quaternion.identity);//previewModel
    146.             _instPreviewObj.transform.parent = transform;
    147.             //rend = _instPreviewObj.GetComponent<Renderer>();
    148.             //rend.sharedMaterial = _materia[1];
    149.             _isPlacing = true;
    150.             currentState = State.Placing;
    151.             _touchPressedAction.started += OnPlacing;
    152.         }
    153.  
    154.     }
    155.  
    156.     public void ConfirmPlacement()
    157.     {
    158.  
    159.         if (currentState == State.HoldPlacing)
    160.         {
    161.             DisablePlatformCanvas();
    162.             _isPlacing = false;
    163.             //rend.sharedMaterial = _materia[0];
    164.  
    165.             _instObj = Instantiate(_tower, _instPreviewObj.transform.position, Quaternion.identity);
    166.             Destroy(_instPreviewObj);
    167.             _CharConfirmPlacementCanvas.SetActive(false);
    168.             _touchPressedAction.canceled -= Hold;
    169.             currentState = State.Default;
    170.         }
    171.  
    172.     }
    173.  
    174.     public void OnCancelPlacement()
    175.     {
    176.         _touchPressedAction.started += OnPlacing;
    177.         _CharConfirmPlacementCanvas.SetActive(false);
    178.         _instPreviewObj.SetActive(false);
    179.         currentState = State.Placing;
    180.     }
    181.  
    182.     public void Hold(InputAction.CallbackContext context)
    183.     {
    184.         if (currentState == State.Placing)
    185.         {
    186.             _touchPressedAction.started -= OnPlacing;
    187.             currentState = State.HoldPlacing;
    188.         }
    189.     }
    190.  
    191.     public void OnPlacing(InputAction.CallbackContext context)
    192.     {
    193.         Debug.Log("Placing");
    194.         if (_instPreviewObj != null)
    195.         {
    196.             _instPreviewObj.SetActive(true);
    197.             _position = _mainCam.ScreenPointToRay(Touchscreen.current.position.ReadValue());
    198.             rayCastHit = Physics.Raycast(_position, out RaycastHit raycastHit, maxDistance = Mathf.Infinity, _layerPlatform);
    199.             if (rayCastHit)
    200.             {
    201.                 _instPreviewObj.transform.position = raycastHit.transform.position;
    202.                 Debug.DrawRay(_position.origin, _position.direction * 20, Color.red);
    203.                 Debug.Log("Touch Started");
    204.                 _touchPressedAction.canceled += Hold;
    205.             }
    206.         }
    207.  
    208.     }
    209.  
    210.     void EnablePlatformCanvas()
    211.     {
    212.         foreach (GameObject platform in _meleePlatform)
    213.         {
    214.             canvasEnabler = platform.GetComponent<CanvasEnabler>();
    215.             canvasEnabler.EnableCanvas();
    216.         }
    217.     }
    218.  
    219.     void DisablePlatformCanvas()
    220.     {
    221.         foreach (GameObject platform in _meleePlatform)
    222.         {
    223.             canvasEnabler = platform.GetComponent<CanvasEnabler>();
    224.             canvasEnabler.DisableCanvas();
    225.         }
    226.     }
    227. }
    228.  
     

    Attached Files:

    • tw1.png
      tw1.png
      File size:
      170.6 KB
      Views:
      8
    • tw2.png
      tw2.png
      File size:
      141.7 KB
      Views:
      7
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Sounds like you have a bug!

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

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

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    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 names of the GameObjects or Components involved?
    - 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.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    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.

    Visit Google for how to see console output from builds. 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 for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    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.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    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:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.



    Once you learn more about what is actually happening...

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?
     
  3. unity_6103548EB384C2C58CE0

    unity_6103548EB384C2C58CE0

    Joined:
    Feb 3, 2023
    Posts:
    3
    i tried debugging what game object im pressing when i press the tower selector, and when i press the tower 2 it debug the name of tower 1. im confused why this is. im pressing tower 2 yet what is executing is tower 1. and since i use the new unity input system i set up a action for left mouse button and set also set the control path on the on-screen button to be left button mouse when pressing which tower im going to put. But when i click the left mouse button tower 1 and 2 is executing at the same time. sorry for my explanation.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    InputAction is global.

    Every script listening to it will receive messages such as OnPressed()

    Your OnPressed() needs to make sure you are clicking on this tower.

    If you're not clicking on this tower, don't do the actions for it.

    There's lots of tutorials for that. Start there. It won't just be code.