#💻┃code-beginner

1 messages · Page 590 of 1

polar acorn
#

Then you've got multiple copies of this script that are all running their click code

#

Because you've got multiple logs saying they've detected clicks

ashen frigate
#

im using player input manager but i dont think thats the problem

polar acorn
#

It demonstrably is your problem. If you're clicking one time, then your screenshot proves this is the case

#

You're getting multiple logs stating the click was detected

#

so there's multiple things running that line

ashen frigate
#

would holding the button affects it ?

polar acorn
#

No idea. Depends on what getClicked does on NewVirtualMouse

ashen frigate
#

its a new playerinput unity

#

so if i hold it it stay true i think

polar acorn
#

Unity has no components named NewVirtualMouse so I literally cannot know what that function does

#

How about replacing the log with a better one:

Debug.Log($"{gameObject.name} has detected Mouse clicked", this);
ashen frigate
#

no need

#

i hold press it and got jambo log

#

so its a hold problem probbly

#

`public void OnClick(InputAction.CallbackContext context)
{
Clicked = context.ReadValue<bool>();
//Clicked = context.action.triggered;

if (Clicked)
    Child.GetComponent<Image>().sprite = clickCursor; // שינוי תמונת ה-Child
else
    Child.GetComponent<Image`
sterile radish
ashen frigate
#

is it readvalue for 1 press ?

polar acorn
polar acorn
sterile radish
cosmic dagger
polar acorn
cosmic dagger
sterile radish
sterile radish
west radish
#

public void Heal(float value) => CurrentHP = Mathf.Min(CurrentHP + value, MaxHP) if it's of any help, this is how I have my own healing code that makes sure it never exceeds the max value

#

Mathf.Min will return whatever is smaller, so if given (125,100) it would return 100

#

the Min and Max functions are quite helpful for logic like this

#

I think part of the problem youre having is while (health < Maxhealth). If health = 100 and MaxHealth = 100, then the condition will enter because health is not actually less than the max

#

health gets to 100, then heals by 25, and only now will that condition no longer be met

sterile radish
#

yes, i changed the line but the issue still seems to be occurring. its hard to describe but even on the first loop of the while loop the health gets set to 125 and im not sure how, the health should just be 25 if that makes sense?

cosmic dagger
cosmic dagger
sterile radish
#

oh sorry its the same code it just copy and pasted weird idk why

#

i see what you mean now

cosmic dagger
#

I think the issue is that tile.Heal() runs multiple times. In Update you check if its health < 0, but the coroutine doesn't add 25 until after 2 seconds. Update runs every frame, so . . .

sterile radish
#

yes, i think that seems to be the issue ive been trying to avoid. i think ill just seperate my logic form the update loop completely. thank you for the advice!

cosmic dagger
cosmic dagger
cerulean badger
#

if I disable an object via script, then reactivate it, will the scripts inherited to the object come back working too or not?

cosmic dagger
#

Scripts aren't inherited to GameObjects (that was my confusion). They are separate components attached to a GameObject . . .

#

Basically, a GameObject is a container storing a list of components; that's it.

sterile radish
cosmic dagger
sterile radish
#

okay thank you, i see it now

misty meteor
#

ok i am having an issue. i got this script to turn on and off my flashlight. i also have a script on my player to not destroy my player nor flashlight. my flashlight will work in the first scene, turning on and off. but when going to my second scene my flashlight is still on my player but the script to turn it on and off no longer works

#

first scene it works

vivid cedar
#

how do i fix?

verbal dome
cosmic dagger
rich adder
cosmic dagger
#

Strike three, you're OUT!

vivid cedar
#

so how do i adda cooldown to a hitsound?

rich adder
#

switch it to a coroutine? or make a timer in Update

cosmic dagger
verbal dome
# misty meteor

How are you preventing them from being destroyed? DDOL?
Is the flashlight a child of the player? What object is the ToggleLight script on, what does your hierarchy look like?

vivid cedar
misty meteor
#

the flashlight and script are both childs of the player

#

which is weird because the flashlight stays and so does the script

#

but the script no longer works??

cosmic dagger
misty meteor
#

ToggleLight is attached to the flashlight, which is a child of the player

#

which the ddol script is attached to

verbal dome
#

And LightSource is a child of the flashlight?

misty meteor
#

yep

cosmic dagger
misty meteor
#

okay i just fixed it actually. so apparently the flashlight script was working but I just needed to move the light forwards a bit because it was stuck in the flashlight?? but it worked in the first scene...

#

thank you though haha @cosmic dagger @verbal dome

#

i was stuck for like 20 minutes

vivid cedar
rich adder
rocky canyon
#

how does this seem for organized bits of an IInteractable setup

cosmic dagger
# rocky canyon

I would swap IStateInteractable to IInteractableState and change IInteractionList because you're not storing an actual list but an array. You can use Collection, Group, or Set instead . . .

IInteractableCollection : IInteractable
IInteractableGroup : IInteractable
IInteractableSet : IInteractable
rocky canyon
#

does sound better.. 1 sec let me get this switch script saved and in tested

delicate portal
#

Works thanks

rocky canyon
#

needed something to give my Switches a bit more info to them..

#

so w/ teh Description and the Hint i can use UI popups w/ each switches name, etc

#

got 1 script doing lots of stuff 😅

naive lion
#

can u expose a nested array in the editor??

lament harness
#

how do you make a class singleton

polar acorn
rich adder
rocky canyon
#

then u can simply use : Singleton<YourScript>

#

extremely helpful as long as u dont go crazy with em 🤪

astral falcon
molten dock
#

i wanted to save all the things that changed in my scene during gameplay so i thought id use loadscenemode.additive to load the minigames

#

however the scenes intercept eachover so it becomes a mess

polar acorn
#

Yeah, that's what additive scene loading is, it adds the new scene to the current one

lament harness
#

so i have to make the static class singleton somewhere
and then I can use it?

molten dock
#

yes, so what should i be doing instead

timber tide
#

do you care for deloading the previous scene

#

if not, just disable it

molten dock
#

i can disable the scene?

timber tide
#

Well, disable components of the scene that would be causing problems, because why would you use additive in the first place if you wanted to remove everything

molten dock
#

if i could set the scene to inactive then it would keep all the changed stuff the same for when i want it

timber tide
#

Not sure if you can just deactive a scene as is, so you may need to throw everything into an empty mono behaviour and deactive that

astral falcon
#

I wonder what you wanna save in playmode that you dont have access too in edit mode. Values on a script?

molten dock
#

removed objects need to stay removed and values need to be kept

astral falcon
#

So you are doing your level setup in playmode or what exactly?

molten dock
#

the player can pick up objects which then get removed from the scene

tawdry rock
#

Anyone know how can i access this RectTransform option via code? (when you press left alt to stretch)

swift crag
polar acorn
tawdry rock
#

i tried something like .GetComponent<RectTransform>().anchorMin = new Vector2(1f, 1f);

#

nothing happened tho

astral falcon
polar acorn
#

Once you change the anchors, you'll need to also change the anchoredPositions

polar acorn
molten dock
#

when i load a scene for a minigame and then leave the minigame the original scene is then restarted

astral falcon
astral falcon
polar acorn
#

This is assuming you have no functionality that depends on OnEnable or OnDisable

molten dock
#

I have decided to include the mini games in the main scene as under a parent object each

molten dock
polar acorn
# molten dock I did think of that but don’t know how I will re activate the map afterward

Objects that are disabled can still run functions you've defined. You can have whatever object is supposed to change back to that scene reference it and re-enable it. You'll need some way of getting a reference to it, probably the easiest way would be to make it a singleton, but that assumes there will only ever be exactly one scene that needs to be "paused" this way

cerulean badger
#

when I use "this" in the script it returns the object as a GameObject or Transform?

polar acorn
#

It returns the script

cerulean badger
#

oh ok

cerulean badger
#

my hierarchy is gone help

polar acorn
cerulean badger
#

thx

wanton epoch
#

!code

eternal falconBOT
wanton epoch
#

So, ive been trying for a while to make my player be able to jump only when he is grounded. Now this code works on another map that I have tried but for some reason doesnt work on another one. Ive used debug logic to figure out that the issue is that i am not being considered "grounded" when I should be i have tried adjusting player settings, tweaking the way detection for being grounded works but nothing is working. I also made sure that the layer mask of "whatIsGround" is applied. Would really like some help on this issue:

https://paste.mod.gg/plxcrwwmbepw/0

modest linden
polar acorn
# wanton epoch So, ive been trying for a while to make my player be able to jump only when he i...

Before your grounded raycast, add this snippet:

foreach(RaycastHit hit in Physics.RaycastAll(transform.position, Vector3.down, PlayerHeight * 0.5f + 0.2f)){
  Debug.Log($"Raycast detects object {hit.gameObject.name} with layer {LayerMask.LayerToName(hit.gameObject.layer)}, Passes mask? {whatIsGround == (whatIsGround| (1 << hit.gameObject.layer))}");
}

It's going to absolutely spam the console, so you might want to turn on Collapse if it's not already on

polar acorn
#

Any time this object stops contacting an object tagged "Floor" it will fire that condition

modest linden
#

So i try walking in the game and and i start falling in the map

wanton epoch
polar acorn
wanton epoch
#

alright

#

Assets\Scripts\PlayerMovement.cs(46,188): error CS1061: 'Collider' does not contain a definition for 'layer' and no accessible extension method 'layer' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)

polar acorn
#

bah, never code without an IDE kids. .collider.gameObject.layer for those

modest linden
#

Because it has a PlayerMovment script

polar acorn
#

PlayerMovement is a pretty common thing to name a script that moves a player

wanton epoch
#

So i just tried it and im not getting any debug logs. just to make sure, this is the line I wrote:

foreach (RaycastHit hit in Physics.RaycastAll(transform.position, Vector3.down, PlayerHeight * 0.5f + 0.2f))
        {
            Debug.Log($"Raycast detects object {hit.collider.name} with layer {LayerMask.LayerToName(hit.collider.gameObject.layer)}, Passes mask? {whatIsGround == (whatIsGround| (1 << hit.collider.gameObject.layer))}");
        }
late burrow
#

does canvas object covering entirety of other objects turn them inactive?

polar acorn
#

Regardless of layer

wanton epoch
#

How is that possible if I am standing on a floor?

late burrow
#

debug drawray your raycasts

polar acorn
wanton epoch
#

Is there any way to visualize a raycast?

late burrow
#

yes drawray

wanton epoch
#

I checked btw, if im free falling, I get this log|

Raycast detects object PlayerObj with layer Default, Passes mask? False
UnityEngine.Debug:Log (object)
PlayerMovement:Update () (at Assets/Scripts/PlayerMovement.cs:46)

but nothing if I am on something. even a new p[lane

polar acorn
wanton epoch
#

you mean like creating a new layer mask just for the player? and making the raycast hit that instead of my ground later?

wanton epoch
polar acorn
#

Is playerHeight the value you think it is?

wanton epoch
#

ill try and figure out this Draw Ray thing

wanton epoch
#

im sorry ill try again

#

bruh i think i fixed it

#

my player height was too low.....

#

For some reason, it needs to be at lesat 2.8

#

but on another map, I can go as low as 0.5

rich ice
#

sorry, just need a link to the !cs server

eternal falconBOT
merry roost
#

Anyone knows how else am i able to edit script? I clicked on it but nothing opens up, i also changed unity > preferences to VS code but am still unable to open a script

late burrow
#

can i set negative time for audiosource

supple wasp
#

hi

wintry quarry
late burrow
#

im getting this but i dont know if its "me" issue or it supposed to not work that why i ask here

C:\build\output\unity\unity\Modules\Audio\Public\sound\SoundChannel.cpp(345) : Error executing result (An invalid seek position was passed to this function. )

merry roost
rich adder
#

double click it

#

screenshot your preferences page in unity @merry roost

merry roost
supple wasp
#

Hey, can you help me with this? I have 2 codes that I want one to connect to the other, the one that is going to be connected I want to make it not do anything when the other is being used and when it finishes using the other code it goes back to how it was before.


public class MoveAndRotate : MonoBehaviour
{
    public float moveSpeed = 5.0f; // Velocidad de movimiento
    public float sensitivity = 3.0f; // Sensibilidad del mouse
    public float minY = -80f; // Límite inferior de rotación
    public float maxY = 80f;  // Límite superior de rotación

    private float rotationX = 0f;
    private float rotationY = 0f;

    void Update()
    {
        // Movimiento con WASD
        float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; // A/D
        float moveZ = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; // W/S

        Vector3 move = transform.right * moveX + transform.forward * moveZ;
        transform.position += move;

        // Rotación con el mouse (solo si se mantiene presionado el botón izquierdo)
        if (Input.GetMouseButton(0)) 
        {
            float mouseX = Input.GetAxis("Mouse X") * sensitivity;
            float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

            rotationY += mouseX; // Rotación en Y (izquierda/derecha)
            rotationX -= mouseY; // Rotación en X (arriba/abajo)

            // Limitar la rotación vertical
            rotationX = Mathf.Clamp(rotationX, minY, maxY);

            transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
        }
    }
}```
rich adder
supple wasp
#

!code

eternal falconBOT
supple wasp
rich adder
merry roost
#

Ive restarted but doesnt seem to work. My VS code seems fine too

rich adder
merry roost
supple wasp
#

Hey, can you help me with this? I have 2 codes that I want one to connect to the other, the one that is going to be connected I want to make it not do anything when the other is being used and when it finishes using the other code it goes back to how it was before.


public class MoveAndRotate : MonoBehaviour
{
    public float moveSpeed = 5.0f; // Velocidad de movimiento
    public float sensitivity = 3.0f; // Sensibilidad del mouse
    public float minY = -80f; // Límite inferior de rotación
    public float maxY = 80f;  // Límite superior de rotación

    private float rotationX = 0f;
    private float rotationY = 0f;

    void Update()
    {
        // Movimiento con WASD
        float moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime; // A/D
        float moveZ = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime; // W/S

        Vector3 move = transform.right * moveX + transform.forward * moveZ;
        transform.position += move;

        // Rotación con el mouse (solo si se mantiene presionado el botón izquierdo)
        if (Input.GetMouseButton(0)) 
        {
            float mouseX = Input.GetAxis("Mouse X") * sensitivity;
            float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

            rotationY += mouseX; // Rotación en Y (izquierda/derecha)
            rotationX -= mouseY; // Rotación en X (arriba/abajo)

            // Limitar la rotación vertical
            rotationX = Mathf.Clamp(rotationX, minY, maxY);

            transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);
        }
    }
}```
https://scriptbin.xyz/okuyawapow.cs

Use Scriptbin to share your code with others quickly and easily.

rich adder
supple wasp
#

if you can help me?

polar acorn
celest jay
#

public int value { get;set; } I read somewhere before that we can show this prop in the inspector.

#

how to do that?

polar acorn
#

That will apply the [SerializeField] attribute to the hidden backing field of the property

celest jay
#

thanks

leaden pasture
#

Oh wit didn't see someone else responded

supple wasp
#

I want the one in the link to connect to the one written in the message about which the message is written. I want to set it to deactivate and reactivate when nothing is being done with the other one.

edgy mist
supple wasp
#

si

polar acorn
supple wasp
#

Where do I put that in which part?

polar acorn
#

Wherever you want to enable or disable it

robust harness
#

Im making a turn based combat system and I currently have a function that activates a skill (which is a scriptable object that SkillScriptableObjects controls the data from) If i want to have multiple skill slots instead of 1, how should i go about making it? Do i make a class that stores all the ui elements and the Skill? Here is what im using right now ```cs

public SkillScriptableObject skill;
public TextMeshProUGUI nameText;
public TextMeshProUGUI descriptionText;
public Image attackIcon;
public TextMeshProUGUI mpText;
public TextMeshProUGUI healthText;``` ```cs

public void onSkill(BattleStateManager battle)
{
    bool noMp = StartBattleSpawns.playerUnit.TakeMp(skill.mpCost, battle);

    if (!noMp) 
    {
        Debug.Log("Not enough MP to use the skill!");
        return; 
    }

    bool isDead = StartBattleSpawns.enemyUnit.TakeDamage(skill.attack);
    battle.hpSlider2.value = StartBattleSpawns.enemyUnit.currentHp;
    battle.playerMp.text = StartBattleSpawns.playerUnit.currentMp.ToString();
    battle.mpSlider1.value = StartBattleSpawns.playerUnit.currentMp;
    battle.playerHp.text = StartBattleSpawns.playerUnit.currentHp.ToString();
    battle.enemyMp.text = StartBattleSpawns.enemyUnit.currentMp.ToString();
    battle.enemyHp.text = StartBattleSpawns.enemyUnit.currentHp.ToString();

    if (isDead)
    {
        battle.SwitchState(battle.endBattleState);
    }
    else
    {
        battle.SwitchState(battle.enemyTurnState);
    }```
timber tide
#

Make an array/list much like an inventory

robust harness
timber tide
#

I mean all you really need are more references to more instances of skills, you can even bind them to some central manager script then bind each one explicitly to some input key or using UI buttons

#
public class SkillManager : Monobehaviour
{
  [SerializeField] SkillSO skill1;
  [SerializeField] SkillSO skill2;
  [SerializeField] SkillSO skill3;

  private void Update()
  {
      if(Input.GetKeyDown(Keycode.Alpha1)
      {
          UseSkill(skill1);
      }

      else if(Input.GetKeyDown(Keycode.Alpha2)
      {
          UseSkill(skill2);
      }

      else if....
  }

  private void UseSkill(SkillSO skill)
  {
    //Do stuff
  }
}```
Here's a crude idea
short meadow
#

Hello! It's my first time trying to use UI to pause a game. I have a small game for a jam a guy and I put together and I'm trying to get the menu working.

I have a UIManager empty with this script attached: https://pastebin.com/HED8sJcQ

I've assigned everything in editor. The game is just supposed to sit in the background paused until the person hits play basically. I can hover over my button to see it but clicking doesn't do anything. (It actually makes my character attack in the background).

The game starts in the background before you click play and my Debug.Log in ShowStartScreen isn't ever printing.

I'm not sure what I'm doing wrong here, any help would be greatly appreciated.

rain ginkgo
#

what is it asking for?

timber tide
burnt vapor
# rain ginkgo what is it asking for?

For next time, you have to wrap InteractableObj in typeof() so it uses the type correctly. Even better would be to use the generic type.

TryGetComponent<InteractableObj>(out info);

Considering it can also fetch the type from info since it's predefined, the solution of Mao also works.

short meadow
timber tide
short meadow
timber tide
#

Your update loops are effectively frozen there, so any input polling will not be received

short meadow
#

I'm actually more confused now than I was when I posted because my start function isn't being called, and this is the only script I have that attempts to set timescale so it shouldn't be paused anywhere else even if it affects UI.

timber tide
#

Buttons linked to methods like that should probably still be called, but maybe I'm blind but I'm not seeing any here

#

Oh yeah I see them

#

Yeah those should still work

#

I'm actually not sure if start will be called if it's scaled at 0 on instantiation

#

Start is called on the first update of the script

short meadow
#

I had a variable reference to an unimplemented screen tutorialScreen. I commented it out and the line in ShowStartScreen(); and it's working now.

I had no warnings, errors or anything. I didn't realize an unassigned reference in editor could break your script like that. Wild.

I THINK it's solved for now though at least. -2 hours lol. At least I'll remember this 🤷 next time.

astral falcon
#

Because every null error will break your entire runtime execution. Thats just how it is. So either be sure its there or check for null and skip accessing it if its null to avoid breaking your runtime

short meadow
#

I super appreciate that explanation though. It's good to have it put into words.

astral falcon
#

Not calling out, just pointing out facts, that you might have missed a step in debugging it and therefore I gave the explanation what happens when accessing the refrence not set. Sorry, if that sounded harsh for you, wasnt meant to . I am just a fan of clear words to describe 😄

violet glacier
#

When should I create manager classes? For example should I create MovementManager, AttackManager, TurnManager, ItemManager, if I'm doing a turn based game?

chrome apex
#

So, when modifying scale for a sprite, I can't make it tile with the transform component? I need to actually get and modify the ''spize'' component in the sprite renderer?

grand snow
chrome apex
#

using scale doesn't tile it

#

it just streches it

#

I just modify the sprite renderer.size instead and it works

robust harness
#

If your code has allot of if statements, or logic you dont want to get checked every frame

#

Though if its a very simple system then it doesnt matter

chrome apex
#

On another note, I want to rotate a sprite between two mouse click such that the ends of the sprite are between the clicks

#

I converted the mouse clicks Screen to world point

#

and I get Vector2.Angle

#

and set the Z rotation to it but it doesn't work. How come?

tulip nimbus
#
{
    Vector3 Move = new Vector3(0, 0, transform.position.z + 0.1f);
    transform.position += Move * Time.deltaTime;
}

This is my code, i know its not optimal but after some time my gameobject dissapears and id like to know why that is. im using 2D

hexed terrace
#

Define "disappears"

Destroyed or just moves out of view of the camera?

#

Also, if you're working with 2D, you usually don't want to move on the Z pos (in / out of the screen)

#

2D moves on x/y

tulip nimbus
hexed terrace
#

I haven't made anything 2D .. but I assume Z pos is pretty much ignored

slender nymph
#

it's used for sorting and depth. and if things get too close to the camera or behind its position then it won't render those objects

hexed terrace
#

plane draw distance, same as 3d

#

thought sorting was done with the layer field on the sprite renderer

slender nymph
naive lion
#

hey guys im implementing a screenshot system where the user can download an outfit that they have created
right now i have a UI canvas that pops up with their outfit and a download button
whats the best approach to making it so when they click download, it locally saves that UI canvas as a png

rancid tinsel
#

how can this cause this error

#

if its null it just gets set to null no?

#

here is the whole bit if that matters:

slender nymph
#

item is null there

hexed terrace
#

image or item is null

slender nymph
#

image is null in the else statement too so no matter what it's going to throw

rancid tinsel
#

ahh

#

that makes so much more sense

#

i got tunnel visioned on the image part

hexed terrace
#

I had only looked at the first screenshot

rancid tinsel
#

wait no but that cant be right

#

let me send the whole method

slender nymph
#

it's the only explanation so it is right

hexed terrace
#

prove it to yourself and log it

rancid tinsel
#

!code

eternal falconBOT
rancid tinsel
hexed terrace
#

Debug.Log($"item is null {item == null}");

rancid tinsel
#

so if item is null it cant run

slender nymph
hexed terrace
#

itemList can have empty (null) elements

rancid tinsel
#

oh does it not throw it if the object itself is null?

slender nymph
#

it only throws if you try to access something on a null object. you can pass null around all you want, but as soon as you try to get something from that null object it will throw

rancid tinsel
#

i see, thank you! ill add a null check and return from the list method then

rain ginkgo
#

Do anybody know how components work after initialized?
I keep trying to declare them and assigning some variable to them in the same frame but sometimes it work and sometimes it doesnt, gameobjects also dont seem to work the frame they are created. The variables often seem to be overwritten...

slender nymph
#

show relevant code

rain ginkgo
#

the loop is ran each update
tree ID does not change

slender nymph
#

why would it change? you're assigning its current value?

rain ginkgo
#

oh no i just did that for a breakpoint

#

its just that, for some reason the assigned value of a gameobject.... doesnt assign properly?

slender nymph
#

can you be more specific about wtf you mean by that

rain ginkgo
#

:)
I will just trial and error then
thanks for your help

slender nymph
#

alright, well for future reference, if you cannot actually explain what is happening you're gonna have a hard time getting help. see #854851968446365696 for what to include when asking for help

small remnant
#

hey guys new here just wanted to know why my dash only happens once every 3 or so console prints

slender nymph
#

do you plan on providing context?

rain ginkgo
slender nymph
#

did you actually save the code? because it's unsaved in your screenshot

rain ginkgo
small remnant
# slender nymph do you plan on providing context?

sorry for that, i made a dash script with a coroutine and then called it to a player controller. this is vector 2d with 8 directional movement. i did a print on the coroutine and the code works fine, but the actual dash only happens once every 3 console prints

slender nymph
rain ginkgo
slender nymph
#

no

rancid tinsel
#

what am I doing wrong here? I thought this was how namespaces worked

slender nymph
#

are they in the same assembly

rancid tinsel
#

oh maybe not

rancid tinsel
#

youre prob right ill take a look at that

small remnant
#

this made the character dash once in 4 tries

slender nymph
#

and where do you call dashActive and have you actually done any debugging to find out the state of the variables you are checking to even start the coroutine

small remnant
slender nymph
#

please share all of the relevant !code

eternal falconBOT
burnt vapor
small remnant
# slender nymph please share all of the relevant !code
using UnityEngine;
using System.Collections;

public class Dash : MonoBehaviour
{
    private Rigidbody2D rb;
    private bool canDash;
    private bool isDashing;
    public float dashSpeed = 200f;
    public float dashDuration = 0.2f;
    private float dashCooldown = 1f;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        canDash = true;
    }

    public void dashActive(Vector2 movementInput)
    {
        if (Input.GetKeyDown(KeyCode.Space) && canDash && movementInput != Vector2.zero)
        {
            StartCoroutine(DashCoroutine(movementInput));
        }
    }

    private IEnumerator DashCoroutine(Vector2 movementInput)
    {
        print("Couroutine start");
        canDash = false;
        isDashing = true;
        rb.linearVelocity = movementInput.normalized * dashSpeed;
        yield return new WaitForSeconds(dashDuration);
        isDashing = false;
        rb.linearVelocity = Vector2.zero;
        yield return new WaitForSeconds(dashCooldown);
        canDash = true;
        
    }
}

//

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private IsometricMovement Movement;
    private Dash isDashing;

    void Start()
    {
        Movement = GetComponent<IsometricMovement>();
        isDashing = GetComponent<Dash>();
    }

    // Update is called once per frame
    void Update()
    {
        Movement.Move();
        Movement.Animate();
        isDashing.dashActive(Movement.MovementInput);
    }
}

rain ginkgo
slender nymph
burnt vapor
#

Though I believe it always happens at the end of a frame

#

So it should work fine regardless

#

Not sure what not "responding" is though

small remnant
slender nymph
#

how have you confirmed that

small remnant
#

i printed if the boolean is true or false every time

#

sorry if thats a dum move

#

im kinda new

lone viper
#

public class peterscript : MonoBehaviour
{
    public Rigidbody2D myRigidbody;
    public float flapiness;
    public score score; 
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        score = GameObject.FindGameObjectWithTag("Logic").GetComponent<score>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) == true)
        {
            myRigidbody.linearVelocity = Vector2.up * flapiness;
        }

        
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        score.gameOver(); 
    }
}
#

why do i get this can someone help me?

#

im new

west radish
#

What does the script that has score look like?

lone viper
#
using Unity.VisualScripting.Dependencies.NCalc;
using UnityEngine;

public class pipehotbox : MonoBehaviour
{
    public score score;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        score = GameObject.FindGameObjectWithTag("Logic").GetComponent<score>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == 3)
        {
            score.addScore(1);
        }
           
    }
}
#

i think its this one im not really sure

#

sorry

#

i was following a tutorial but i named things differently

tiny wind
#

how do I trigger the Animator components of an array of GameObjects?

#

oh wait nvm got it

drowsy wraith
#

@lone viper Do you have a score class?

#

also you should get into the habbit of having good name structure it will be very helpful for you in the future

lone viper
drowsy wraith
#

create a seperate script that handles score are you watching a tutorial?

tiny wind
#

how do I make this work?

drowsy wraith
tiny wind
lone viper
#

there shouldnt be any missing script since this is all theyre doing in the video

drowsy wraith
#

Follow what they're doing then but name things properly but as of now you're trying to call score.gameOver but you don't have a method for it thats why you're getting an error

#

you probably missed something in the video

lone viper
#

oke

drowsy wraith
rancid tinsel
#

is this bad practice in any way? was getting annoying ondestroy errors in unity when quitting playmode

#

the Application.isFocused made the errors go away unlike Application.isPlaying

burnt vapor
#

So this creates an edge case

#

That said, XY problem, why do you have these problems to begin with?

rancid tinsel
#

It's not really a problem, it's just that it's a team project and I don't want someone to look for a "false" error

#

I don't understand why there is no option to ignore closing playmode on OnDestroys to begin with

iron wind
#

That sounds more like a problem with your code than OnDestroy

#

What exactly are you trying to do that warrants some OnDestroy not being called when the object is destroyed?

rancid tinsel
#

it is meant to be called when its destroyed

#

while the game is running

#

not when it closes in the editor

iron wind
#

but closing the game in the editor is also destroying all your objects

#

since you are effectively "closing" the game

rancid tinsel
#

sure. but what is the point of that behaviour? what is the use case for OnDestroy triggering when the game shuts down

#

it feels counterintuitive

iron wind
#

OnDestroy triggers when the scene the object belongs to is closed

#

Closing the game down completely also triggers that since you are unloading the scene

rancid tinsel
#

i know

iron wind
#

I don't see how that's counter intutive is what i mean

rancid tinsel
#

OnDestroy -> when you destroy this object, do ...

#

Calling the function you use for in-game stuff when closing the game is weird

#

why not separate the two

#

unless there is something else that works just like OnDestroy that i dont know about

drowsy wraith
#

Application.isPlaying no?

#

instead of isFocused

rancid tinsel
#

that doesnt work

#

i tried it

drowsy wraith
#

So you don't want it to show as you're working on it with other people and they might get confused ?

iron wind
#

maybe you are looking for OnDisable

rancid tinsel
#

essentially yeah, i can also put a comment in but why would Unity throw an error

rancid tinsel
runic lance
#

what is the error by the way?

iron wind
#

yeah that's probably a better question

runic lance
#

I don't see why this behavior is not expected, when the scene is destroyed, the object is destroyed

#

doesn't really matter if the game is closing or not

iron wind
#

I'm guessing the error is that your PopulationManager.Instance is already destroyed

rancid tinsel
#

"Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)"

#

and it refers to the PopulationManager

runic lance
#

then most likely the instance was already destroyed and you're creating a new one, since it's a singleton

rancid tinsel
#

sure but my issue is - how else am I meant to call something when the object is destroyed

verbal dome
rancid tinsel
#

the error is caused because its a singleton and a new one gets generated if its destroyed but the method is called

runic lance
#

you can work around it by storing a reference to the singleton in the class that is being destroyed

runic lance
#

instead of accessing the Instance every time

rancid tinsel
#

how do i call something on when its destroyed though

iron wind
#

I think in this case you'd be better of adding/removing to population manager in OnEnable/OnDisable instead

rancid tinsel
#

the singleton doesnt matter

rancid tinsel
verbal dome
runic lance
#

he's already checking for null there

#

although incorrectly, since accesing the Instance property will always create a new one

verbal dome
#

If it's okay that its null, then sure

rancid tinsel
#

my issue isnt with the singleton behaviour

#

i dont want whats in OnDestroy to ever trigger on game close

#

idk if there is a different method for that

verbal dome
#

Btw Application.isQuitting exists, might be also helpful

runic lance
#

there isn't, when your game closes your scenes get destroyed and everything contained also gets destroyed

rancid tinsel
#

but the idea is, if the object is ever destroyed by whatever, decrease population size and remove it from population list

verbal dome
#

And when the whole game quits, you don't care about removing it from the population, correct?

rancid tinsel
#

i saw this mentioned elsewhere too

verbal dome
#

Oops, *Application.quitting

rancid tinsel
#

oh oops yeah

#

i made that mistake earlier too lol

verbal dome
#

(Weird naming convention from unity, usually their bools start with is)

runic lance
#

IMO the cleanest way to do this would be to store the singleton reference on Awake/Start and then check for null on OnDestroy

rancid tinsel
#

its an "action" it seems

verbal dome
#

Ah it's an event, right

#

I might have hallucinated

rancid tinsel
#

ok i seem to have found a solution

slender nymph
#

this doesn't seem necessary, what issue is this supposed to solve?

rancid tinsel
#

had some help from copilot, and thats what ive got after cleaning it up

rancid tinsel
slender nymph
#

what error

rancid tinsel
#

OnDestroy calls a singleton when game is quit

verbal dome
#

They were accessing an already destroyed singleton in OnDestroy
And accessing it would create it again, which is not allowed from OnDestroy

rancid tinsel
#

which creates a new instance

cerulean badger
#

what's the best option for handling multiple attacks inputs: the old Input class or the InputSystem thing?

slender nymph
rancid tinsel
#

i think the point of the automatic instance creation is for it to not cause errors if someone forgets to add it to the scene

#

the singleton solution we are using wasn't done by me, but a colleague

#

so I wouldn't want to mess with that

runic lance
#

but the issue is that automatic instance creation is not suitable there

#

most likely the issue would also show up if you unloaded the scene manually

verbal dome
rancid tinsel
verbal dome
#

Such as a property InstanceExists or a TryGetInstance method

verbal dome
rancid tinsel
#

either way its basically one case in which its bad, i think its better to just use OnApplicationQuit here

verbal dome
#

Nothing wrong with that IMO

rancid tinsel
#

different question though - how do static variables work? I assumed you couldn't change them at runtime, but clearly in the screenshot I sent that's what it's doing

slender nymph
#

you're thinking of const. static just means the member is not associated with any instance

rancid tinsel
night mural
# rancid tinsel

if you ever have any new entities like this, you'll have to remember to clean them up in the same way which feels fragile too

rancid tinsel
#

what does it mean in practice that its not associated with any instance? does it mean that if I change it, it changes it for every VikingTracker holder?

night mural
rancid tinsel
#

if it was my code I'd dive in but I wouldn't want to touch anything he's worked on myself

#

that sounded bad lol I meant it's his work so I wouldn't want to change stuff without his knowledge*

night mural
#

totally! and collaboration is important

runic lance
#

that's what pull requests are for

night mural
cerulean badger
rocky canyon
#

u can get the job done w/ either system

polar acorn
cerulean badger
#

ok then ty guys

grand snow
#

new is better in the long run

lost torrent
#

i posted this issue im having with my code and got told to configure my IDE. ive followed the steps on the microsoft page called 'Configure Unity to use Visual Studio' by selecting it in my external script editor, updating the visual studio editor package, and updating visual studio but nothing seems to have changed and i still have the same issue. does anyone have any tips or know what to do??

polar acorn
polar acorn
#

Do it while the IDE is closed, then reopen unity and reopen the IDE

grand snow
lost torrent
swift crag
#

Assembly definitions are used to break your code into separate units.

#

Incorrectly set up asmdefs wouldn't completely break your IDE, though

swift crag
#

Newly installed packages can't start doing anything until you resolve that

lost torrent
#

i gave up and just changed the code but thanks for the suggestions i do appreciate it :P

frigid sequoia
#

Before I get to it and totally waste my time; if I Lerp an object posstion, that does not trigger the trail right?

frigid sequoia
#

Yes

verbal dome
#

I don't know why it wouldn't trigger

#

The trail doesn't know/care if the position was lerped or changed in some other way

polar acorn
#

Lerp just gets a value some percentage of the way between two other values. It's not a different method of moving an object

#

It's just a way to compute a value

frigid sequoia
#

I thought trail just activates when you move the thing, not teleport it, which is what a Lerp possition would do

polar acorn
verbal dome
#

With transform, there's reaally no difference in "moving" and "teleporting"

vagrant spruce
#

I'm following the Unity Essentials Pathway on Unity learn and I'm on Mission 4, Step 7. I opened the PlayerController (MonoBehaviour Script) as per the instructions and it's just opened to a blank screen with a toolbar. I'm pretty sure I'm meant to be seeing some starter code but there's nothing. Anyone able to lend a hand?

#

what I'm seeing

wispy wraith
#

!code

eternal falconBOT
rich adder
vagrant spruce
rich adder
#

try close VS click Regen Project files

#

double click script again

vagrant spruce
#

nvm i got it fixed

#

thanks for the help

green badge
#

Does anyone know why when I add a box collider to my tilemap the collider is a big rectangular area and not the individual tiles?

#

Oh got it

echo ruin
green badge
#

thanks bro

twilit sinew
#

So I’ll trying to make an auto player for my black jack game but after one card it just stops hitting or it doesn’t stick / press play again and idk what to do lmk if you need the whole script or just this.

burnt vapor
eternal falconBOT
polar acorn
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

queen adder
#

Is unity's visual scripting still called bolt? Or did they re name it/make a new thing?

#

trying to get back into learning unity now that i've got time but idk where to begni yet. am looking for visual scripting though

slender nymph
#

it's just called Visual Scripting now and there's an entire other server where you can discuss it #763499475641172029

queen adder
#

ok that's very useful information for me than. Thank you.

proud escarp
#

Hey guys! I'm learning Unity, I'm at the very beginning.. I tried to do some targets to shoot, but I see them in this way.. Anyone know why? what might cause that? they are simple 3d objects created directyle from Unity

#

I see them in that way even when I start the game

rich adder
proud escarp
rich adder
#

if you want to change the look just mess whats already inside the material like color / texture

acoustic belfry
#

Hey,

Is there a way to check the hitbox of a character midgame?

I mean cuz i added a meele attackbut i dont know how much large it is

Here's the script btw

#
{
    Collider2D hitEnemy = Physics2D.OverlapCircle(transform.position, attackRange, demons);

    if (hitEnemy != null)
    {
        if (hitEnemy.TryGetComponent(out EnemyBase enemy))
        {
            enemy.TakeDamage(meleeDamage);
        }```
slender nymph
#

you can use the Gizmos class to draw the overlap circle, or use a convenient package like vertx's debugging to draw your physics queries (mostly) automatically

acoustic belfry
acoustic belfry
#

Oh, thanks :3

brittle girder
#

i dont think i did that right

polar acorn
#

!code

eternal falconBOT
brittle girder
#
// [class CreateAssetMenu]
public class CharacterDatabase : ScriptableObject
{
    //creating the different races into an array
    public CharacterSelect[] character

        public int CharacterCount
    {
        get
        {
            return character.Length;
        }
    }

    public CharacterDatabase GetCharacter(int index)
    {
        return character[index];
    }
#

thanks

#

so I'm having an issue where im trying to make a database. after i finished this script and i went back to unity. i right clicked and went to create. and it seems i cant make the character database

#

the option isnt there i mean

polar acorn
#

Why would you expect it to be there?

slender nymph
#

that option is only available when you have a CreateAssetMenu attribute on the class

brittle girder
#

oh i didnt copy it right

slender nymph
#

which you have not completed correctly and also commented out

brittle girder
#

my bad

#

its not commented out on my script thats weird

#

Could you guide me in how to complete it correctly?

slender nymph
#

why not just read the docs?

brittle girder
#

i meant if i could be pointed there

polar acorn
#

You can just search CreateAssetMenu on google

slender nymph
#

or even ScriptableObject because the example for that includes the usage of the attribute

brittle girder
#

thank you boxfriend

fathom bramble
#

I need the static class GameManager to exist right away. Is this the best way to do it?

GameManager.Init() literally does nothing but print "Game Manager is initialized". But I need to call it in order for the static constructor inside to execute its code at all.

verbal dome
slender nymph
#

there is no guarantee when a static constructor is going to be called except that it will always be called before any instance is constructor or any static member is accessed. if you need something to happen before everything else in a static context with no extra code, then use what Osmal suggested instead of relying on the static constructor to be called

fathom bramble
#

Honestly all I'm trying to do

#

is have a GameManager persist through every scene. Is using DontDestroyOnLoad() better for that? I just feel weird attaching a gamemanager to an object in a scene

#

but if that's better practice so be it

slender nymph
#

static constructors and DontDestroyOnLoad solve completely different issues. if you just want it to not be destroyed when you change scene, then yes all you need is to pass it to DontDestroyOnLoad

#

if you just want to spawn the object and mark it as DDOL any time you launch the game then use the attribute osmal linked to do that initialization

fathom bramble
#

The only reason I used a static constructor is that I want my GameManager to subscribe to events that I plan to fire (like a GameOver event)

With other gameobjects, I use Awake()

#

but since my game manager isn't a regular game object, I couldn't

#

but I guess it can be

slender nymph
#

it doesn't need to be. use the attribute that was suggested

fathom bramble
#

is it some preprocessor thing?

grand snow
#

Attributes!

proud escarp
#

Hey guys! Is there a way to detect if I have only clicked (and released) or if I'm holding the left click with the new unity input system?

    [SerializeField] private InputActionAsset PlayerControls;
    private InputAction shootAction;

    void Awake()
    {
        shootAction = PlayerControls.FindActionMap("Player").FindAction("Shoot");
        //shootAction.performed += _ => FireWeapon(); // When clicked
    }
#

Or do I have to do manually, like setting a variable isShooting to true when performed and to false when canceled?

rich adder
wintry quarry
#

Not events

#

The events will only tell you when something changes

rich adder
#

if you want hold behavior on button set it from Button to Any Value then you can use Started,Canceled to set a bool

proud escarp
timber tide
#

could also do a coroutine and cancel it when not holding and things like that but update is fine

wintry quarry
#

The new input system provides flexibility

#

Event based handling is just one option it offers

proud escarp
#

I thought it was something like an optimized way to handle performed actions, instead of checking them every frame in the update

#

I guess I'll do what's easier to understand for me now, like maybe a variable saving that state

wintry quarry
timber tide
#

I'd argue that it's not some extreme optimized solution from the older input system. It's cleaner and allows for quick key rebinds that's for sure

proud escarp
wintry quarry
#

The events are still being checked every frame

timber tide
#

I'd suggest just poll the input if you're not too aware of events if you want to get started on something

#

using the legacy input system

proud escarp
#

I understand, I thought there was some kind of optimization underneath lol but yeah it surely make the handling more cleaner

wintry quarry
#

Performance was never the concern

proud escarp
#

btw I'm looking inside the InputAction class, and I'm finding some events which would maybe help on that

rich adder
proud escarp
rich adder
sacred cradle
#

how can i set a particles velocity to the emitters when the particle is spawned?

#

possibly without a script?

#

oh

#

i found

#

ty

tulip stag
#

Hey! It's my first time using the whole get; set; thing and I'm a bit lost on what's the proper syntax for what I'm trying to do. I've read the debug errors and I think I get the gist but I'm still lost.

slender nymph
#

you've redeclared the maxHP variable as a local variable inside of the setter but also it's after you attempt to use it

#

remove that extra declaration, make sure to return maxHP in your getter too
oh and your property (which is what you referred to as "the whole get; set; thing") is private

fringe plover
#

guys can someone help please

        var writeTask = File.WriteAllBytesAsync(Global.TempZipPath, request.downloadHandler.data);
        yield return new WaitUntil(() => writeTask.IsCompleted);

This thing results file being created like normal in Editor
But in builds it creates file with 0 bytes

#

i did log how many bytes i download, its not 0

naive pawn
slender nymph
#

oh yeah that too, completely slipped my mind lmao

tulip stag
slender nymph
#

your assignment is backwards too, but yes

tulip stag
slender nymph
#

or wait no this whole setup is confusing because you don't seem to understand how properties work

tulip stag
#

I don't :P It's my first time using them. I've read the documentation but I'm still lost

slender nymph
#

you need to declare a field to store the value of your currentHP because the property itself doesn't hold the value, the backing field does

tulip stag
#

What I'm trying to achieve is simple: when I write into currentHP, make sure it never exceeds maxHP

grand snow
#

I feel like a function is easier to start with instead of a property

tulip stag
#

IS THAT SO?

slender nymph
#

yes, properties are basically just methods that look like variables

tulip stag
#

if that's the case I'm cooked— I've been {get; set;} damn near every variable in the entire project

hot laurel
#

thats just syntatic sugar for 2 methods(getter and setter) with backing field

deft siren
#

i tried doing this simple lightswitch code but for some reason it doesnt work, the icon appears so it its conisdering itself inside the trigger but when i press E nothing happens

grand snow
#

thats an exception. {get; set;} makes the backing field for you internally by magic

slender nymph
tulip stag
#

This is what the average class in my code is looking like

slender nymph
#

those are all auto properties which means the compiler creates the backing field for you

rich adder
hot laurel
#

well those properties set and get have empty bodies, why not to use just public fields then

slender nymph
#

most of them are likely from the interface which requires using properties because interfaces cannot have fields

tulip stag
slender nymph
polar acorn
tulip stag
grand snow
#

I would do:

public int HP
{
    get => _hp;
    set => _hp = Math.Min(value, maxHP);
}

private int _hp;
private int maxHP;
tulip stag
#

Something else that's been puzzling me is this compiling error in particular.

slender nymph
# tulip stag Mhm, that's partially it. For the others, it's simply because I've been told it'...

that is for sure the way to go about it, you just need to understand how properties actually work.
I don't normally do this because i hate spoon feeding, but this will explain how you should structure your property (also i will be using proper name conventions rather than what you are using):

[SerializeField] private int _maxHP; // this is obviously the field you are using to validate the property's max value
private int _currentHP; // this is the explicit backing field, in other words this field is what is actually holding the value that is returned by the getter for the following property
public int CurrentHP // property declaration
{
  get => _currentHP; // you have to return the value of the backing field in the getter to provide the correct value when getting the property
  set => _currentHP = Mathf.Clamp(value, 0, _maxHP); // this assigns to the backing field using the `value` keyword which is what contains the value being assigned to the property, i've used Clamp here to make this shorter since you probably don't want it below 0 anyway
}
slender nymph
tulip stag
slender nymph
#

once that version of the language becomes available though, we won't need our full properties to have an explicit backing field anymore which will be convenient

slender nymph
tulip stag
#

Ok bet 🫡

grand snow
#
[field: SerializeField]
public int FooBar {get; private set;}

something else fun you can do with properties

slender nymph
#

yeah that's nice for modifying the propery's value in the inspector

tulip stag
grand snow
tulip stag
#

So, my only question right now is: Now that I have a backing field and a property with Get; Set;, how do I interact with this in other parts of my code? Let's say I need a function that displays my HP. Which one do I call, the backing or the property?

rich adder
#

ideally the property that should be Get public only

#

one of the main benefit of props is to give write access to its own script while keeping outside scripts on a Read only requirement

#

if you have extra logic to run in the Property then always grab/set the prop if its Get or Set

#

normally your backing field is only there to set values within its own class

tulip stag
#
        int maxHP;
        int tempMaxHP;
        bool hasTempMaxHP;
        int tempHP;
        int _currentHP;
        int currentHP
        {
            get
            {
                return _currentHP;
            }
            set
            {
                if (tempMaxHP > 0)
                {
                    if (value > maxHP + tempMaxHP)
                    {
                        _currentHP = maxHP + tempMaxHP;
                    }
                }
                else
                if (value > maxHP)
                {
                    _currentHP = maxHP;
                }
            }
        }```Is this better implementation? :> Did I succeed
grand snow
#

clamp() will make it a lot easier to maintain

rich adder
#

also can benefit from props using correct casing

grand snow
#

i presume you want Mathf.Clamp(value, 0, hasTempMaxHP ? tempMaxHP : maxHP)

rich adder
rocky canyon
#

are all the variables ment to b private?

tulip stag
remote lynx
#

camelCase the goat

rich adder
rocky canyon
#

camelcase is great.. but public could be Pascal

remote lynx
#

i hate c# naming conventions lol

remote lynx
rocky canyon
#
private int currentHP;

public int CurrentHP
{
    get => currentHP;```
tulip stag
#

I usually use pascal for methods and classes. I assumed vars in general were camelcase

rocky canyon
#

looks better imo

rocky canyon
grand snow
#

haha people do whatever they want

rich adder
#

the whole point of convention is to be able to tell right away at glance what the thing is, no one is forcing you to

grand snow
#

private myVar 😀

private m_myShitVar 🤮

rich adder
#

the unityWay ™️

grand snow
#

m_ can go die in a fire

#

its 2025 we dont need to prefix var names with dumb info like unreal engine

rocky canyon
#

if u still use m_ ur trying to be hipster

grand snow
#

b_myBool 🙃 🔫

rich adder
#

I think its people in the backend are working on C++ and can give a shit about C# conventions lol

grand snow
#

it seems to change on a whim what conventions they use

rich adder
#

cinemachine had a mix of Props and Public fields, it was a weird flex lol but that was a bought asset so it doesn't count ig

drifting onyx
#

hey guys, im having an issue where a public feild assigned in the inspector becomes a null value when i run the program, spent the last hour looking between the two scripts and their isnt something that should be messing with it like this, is there some setting or something I fucked up?

rich adder
tulip stag
#

One "typical" naming convention I know is right but I just don't like and opt not to use is saying something like n instead of number for local methods

#

Looks bad to the eye idk 😔

frigid sequoia
#

How did I like replace an asset from another without losing the references?

rocky canyon
#

copy the fields

frigid sequoia
#

Like in, I just updated an image and want to replace it

rocky canyon
#

and paste em in

frigid sequoia
rocky canyon
frigid sequoia
#

I don't wanna copy a component, I want to update an asset with a newer version of it

rocky canyon
#

oh..

slender nymph
#

that doesn't sound like a code question.

#

and if you have an image file that you want to update, just . . . save over the existing one. that's literally it

frigid sequoia
#

Where do I ask that then?

rocky canyon
#

if the name of hte image is still the same.. updating it should keep the reference..

frigid sequoia
rich adder
#

replace it in FileExplorer

slender nymph
#

it needs to literally replace the existing file. or you can just rename the old one's meta file to be the same as the new one 🤷‍♂️

frigid sequoia
slender nymph
#

it does

#

the only reason you might not see it update immediately in unity is if you turned off the automatic asset refresh. but that would be your fault, and not because it isn't actually updating.

frigid sequoia
#

I have not touch anything like that

#

It's that off by default?

slender nymph
#

then saving over the existing file will JustWork™️

slender nymph
static cedar
#

I thought id have file scoped namespace in Unity 6. I remember creating a new project in beta and had that.

deft siren
#

simple, on and off sistem but for some reason it doesnt work

#

the icon appears so it is checking that i enter the collider

wintry quarry
deft siren
#

a point light

wintry quarry
#

So aren't you deactivating the whole object?

#

That means Update won't run

deft siren
#

oh im sorry my mistake

#

its attatched to a lamp

#

the object its trying to turn off is a point light

wintry quarry
#

Adding Debug.Log will help you understand what is going wrong here

#

Also you didn't really explain which part of this isn't working

#

What ar you expecting to happen that isn't happening?

deft siren
#

the gameobject doesnt turn off/on

slender nymph
wintry quarry
#

Which one

deft siren
#

the lamp

wintry quarry
#

Make sure you have the correct object referenced

deft siren
#

the icon appears and dissapears

wintry quarry
#

and that you're looking at the correct inspector

#

Also make sure the object that this script is attached to is active at all times, and that the script is active at all times

polar acorn
deft siren
#

i got it

#

sorry for the trouble

static cedar
polar acorn
#

!code

eternal falconBOT
slender nymph
rich adder
#

gotta wait for the CoreCLR switch

static cedar
#

I'm just saying, i can still use file scoped namespace as long as I set the lang version.

dusty crypt
slender nymph
dusty crypt
rich adder
slender nymph
dusty crypt
#

so how do i make it go straight after it spawns in front of the player?

slender nymph
#

obviously don't assign it to the player's position every frame

#

also if it has a rigidbody on it why are you moving it via the transform?

dusty crypt
#

how should i move it?

slender nymph
#

using the rigidbody

dusty crypt
#

ill take a look

lone viper
#

does someone knows how to get rid of this white border thingy

#

im pretty sure its from the canvas

#

or

#

sth

#

idk how to get rid of it safely

#

tho

rich adder
#

also not a code question

lone viper
#

sorry

#

i didnt know where to even ask this

rich adder
ember tangle
#
collider = GetComponent<MeshCollider>().sharedMesh;

//generate mesh that works 100%

collider = mesh;```
The collider shows nothing in the mesh field in the editor.
#

why is this?

slender nymph
#

are you actually assigning it back to the mesh collider? or are you expecting the collider variable to somehow assign the mesh to the sharedMesh property of the meshcollider?

ember tangle
#

I am assuming that the shared mesh is supposed to be a reference to the mesh.

slender nymph
#

sure, but are you actually assigning to that property anywhere

ember tangle
#

collider = mesh;

slender nymph
#

that is assigning to your collider variable

ember tangle
#

collider = GetComponent<MeshCollider>().sharedMesh;

slender nymph
#

here's a thought experiment for you:

string one = "one";
string two = one;
two = "two";

what does the variable one contain after this code executes

ember tangle
#

GetComponent<MeshCollider>().sharedMesh = mesh?

#

It worked.

small dagger
#

Hello, I am trying to figure out my character movement right now, I am using rigidbody addforce to move. My issue is, when I run onto a slope, even a minor incline, the movement slows way down, any suggestions on a fix?

rich ice
#

well, first of all you should send the !code if you want us to help with it

eternal falconBOT
rich ice
#

and secondly. you should have the character move along the surface normal and then divide the movement force by some dampener as the slope increases

untold shore
#

Hey y'all. Something weird is happening with my code. It's accessing my code and turning a variable into the thing it should, but then is immediately returning it back to 0. I want it to be 4, and it does it for only one frame. Any ideas of why? I have no idea what could be causing it.
The code: https://paste.ofcode.org/vumCBRZUfGp8pHAA8hkaWf
The reseting works, only turning it to 4 does not, as seen above. (please @ me if you respond! Thanks)

odd grotto
#

camelCase is overrated we should switch to raNdoMCasE

cosmic dagger
untold shore
cosmic dagger
#

also SerializeField is used to store (save) private fields and display them from the inspector. public fields are serialized by default . . .

untold shore
#

Also apologizes if I seem rude, I dont mean to be! Currently freaking out as this just broke whenever it's due for a school competition tomorrow.

cosmic dagger
untold shore
#

Currently it's only saying (in the code) that its referenced by the BetManager code (the first one I showed you. Checking everything else just in case

cosmic dagger
small dagger
#

is there any way to make the jump action starting on line 43 more fluid? Right now, when I hit the jump button, I pretty much just teleport up to the jump height instead of travelling through the air

maiden relic
#

can someone please help me I am getting so pissed off. Why is my child controlling my parent objects transformation?

#

when I move the childs position it moves its parents position with it

cosmic dagger
small dagger
wintry quarry
#

neither deltaTime nor fixedDeltaTime should be used

#

also the reason your jump feels like a teleport is because of line 40

#

you are overwriting your velocity completely every frame

#

so the force only gets a chance to matter for one physics frame

small dagger
#

gotcha, thanks will try to fix this

untold shore
#

Also hey PraetorBlue!

maiden relic
#

I have a gun object (position) another object (pivot point) and I made one gun using this set up and the pivot is on stock of gun and position is in center of gun and it works. tried adding another gun and when I move child for example the gun inside the pivot point the pivot point moves with the gun and same for moving the pivot it moves the position (parent)

#

top works

split venture
#

Does anyone know a good tutorial for FPS movement? I followed Brackeys FPS and got liked it, but noticed it had issues like falling incredibly fast if something didn't have a certain layer, and if you held A & D to move you would go 2X the regular speed.

exotic jacinth
#

My enemy isn't moving to a random point so I decided to draw the ray to check the point but I cant see the ray in the editor

#

gizmos are on

cosmic dagger
exotic jacinth
#

this the code

cosmic dagger
untold shore
#

Hey RandomUnityInvader(), figured out the problem and wanted to say thanks for the help. Turns out the button was calling on the script on the asset folder, not in the game 😅 Also, thank you so much for the past help that youve done!

cosmic dagger
exotic jacinth
cosmic dagger
exotic jacinth
#

Thanks for the help , it worked

cosmic dagger
#

Nice!

untold shore
cosmic dagger
#

Yes, you should normalize the result, but only if you want to use a distance. This will still display the direction correctly . . .

static cedar
#

I set up a nested rigidbody 2D. The uppermost is dynamic, the rest are kinematic.
I noticed that the dynamic rigidbody doesn't utilise the colliders that attached to the child rigidbody.

#

Is that normal behaviour?

#

This isn't an issue, since i'm planning on using them for animation and have a separate collider for interacting with walls.

slender nymph
#

yes, they are considered separate rigidbodies, colliders are only part of the closest ancestor rigidbody's compound collider

hallow sun
#

For some reason transform.position = Vector3.zero; prevents transform.SetParent(null);
Does anyone know what is going on here, and how to fix it?

hallow sun
#

testing. i used to have a problem with double triggering a function, that why i added the transform.position

slender nymph
#

what do you mean it prevents transform.SetParent, that makes no sense

hallow sun
#

i just fixed the issue by using setactive(false) instead but its still weird

hallow sun
rich adder
#

how did you verify the function is running

slender nymph
#

how have you actually confirmed any of this

hallow sun
#

everything else in that function runs fine

slender nymph
#

show the full code

hallow sun
#

by testing yeah, if i remove the transform.position line setparent(null) works again

slender nymph
#

and explain how you have actually confirmed this. because what you have said makes no sense

hallow sun
#

the relevant code:

public override void GiveFood(Food_Base _item)
{
    // Eat
    _item.transform.position = Vector3.zero;
    _item.transform.SetParent(null);
    _item.gameObject.SetActive(false);
    // Check if correct order
    manager.CheckOrder(_item.order);
}
slender nymph
#

show the full code. because i have a feeling that something else is affecting it since setting the object inactive apparently fixes it

hallow sun
#

something like this:
test 1 (with this code): _item is not removed from its parent, everything before and after works fine
test 2 (remove transform.position line): _item is removed successfully, but triggers CheckOrder twice for some reason

#

Food(Clone) is _item
Making it inactive doesnt solve this problem, it solves the double trigger problem and then i can just delete transform.position since that was its only reason to be here.

slender nymph
#

apparently you don't know what the word "full" means, but i'm not going to bother asking again so good luck getting this figured out

untold shore
#

Hey quick question. Trying to figure out how to skip items in a queue:
I have a queue of 6 items, being the sentences in the boxes photo (following a brackey's tutorial). Currently, I have these items in a queue, however, I want to be able to skip to certain lines when a variable is called. If I remove items from the queue, will it destroy this string list? Or how would you go about skipping lines? Here is how I am storing the string[]:

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting Dialogue with " + dialogue.OpponentName);

        nameText.text = dialogue.OpponentName;

        SentenceQueue.Clear();

        foreach (string sentences in dialogue.sentences)
        {
            SentenceQueue.Enqueue(sentences);
        }

        DisplayNextSentence();
    }
``` Any help is much appreciated. I apologize, Queues are not my thing 😅
slender nymph
#

a queue is supposed to be first in first out, is there a specific reason you're using a queue and not like a list if you want to be able to just skip elements?

untold shore
#

Actually thats fair. More this is what it was already coded on, so Ill probably just have to make a new method real quick. Didn't realize it was first in first out 😭 . Mainly its because of this:

 if (SentenceQueue.Count == 0 )
        {
            LevelContinueButton.SetActive(true);
            EndDialogue();
            return;
        }

Do you think I could make a new queue with specific items from the list? Is that unoptimized?

slender nymph
#

FIFO is the entire point of using a queue

void thicket
#

Just use List ™️

slender nymph
#

Do you think I could make a new queue with specific items from the list? Is that unoptimized?
what are you actually trying to achieve here?
https://xyproblem.info

void thicket
#

It's trivial to make own queue-like system based on List

#

And you take full control

untold shore
#

Here: I want the player to click buttons to go into different dialogue options. It runs through the dialogue, then when player presses continue it goes onto next piece if it has dialogue, or returns to dialogue options if not. I have a list with the sentences already, so i need to just go into that list each time for each specific one, right? Sorry, want to make sure Im getting y'alls idea right

topaz mortar
#

if my player and monsters are moving around in fixedupdate with physics
if I program a player attack, should it also be in fixedupdate? or is it ok to be in update?

slender nymph
slender nymph
topaz mortar
#

it is a multiplayer game, so not sure how that might mess with things

void thicket
untold shore
#

Like this?
https://paste.ofcode.org/j8YpTGSGRrAksrYrXEZeqS
Also, Ive never heard of a dialogue tree. Is there any good resources that you know of for researching that?
(Also, yeah its simple. This is my first coding project for a school competition 😅 ) Thank y'all for the help though, it means so much to me.

void thicket
untold shore
#

Weird thing that is happening now. Currently it keeps saying that my index is out of bounds? I was thinking that the thing would be fine, but its bugging out on me. Here's the code:
https://paste.ofcode.org/m6bH6jNdyN34Qn85tSrKmd
And where it is specifically breaking:

 if (WhoareYou == true)
        {
          (Here)   sentencesaying = Dialogue.sentences[6];
               StartCoroutine(TypeSentence(sentencesaying));
            ContinueButton.onClick.AddListener(EndDialoguePostWin);
            WhoareYou = false;
        }  
``` I don't know, still pretty confused on why it's breaking.
slender nymph
#

remember that arrays and lists start at 0 so their Count will always be one higher than the last index

untold shore
#

Right- That 6 that you see is what the count is. Should I say 5 instead?

burnt vapor
#

5 would be the sixth item

#

Because zero-indexing

#

0 would be the first

untold shore
#

Ohhhh

burnt vapor
#

Consider using a dictionary and listing the dialogue items by a key if you want an easier time getting dialogues

#

Right now you have an index with no clear explanation what it is, which can be confusion

#

Alternative an enum is also nice because you can give a name behind the index

fleet parcel
#

Hey, I am working on a game with a system that requires inputs from the player in order to do an attack (Left arrow, right arrow, up arrow, down arrow like Friday Night Funkin or Dance Dance Revolution) and I am working implementing attack animations to each arrow input. Any idea on how I would set the animation to only play of the last input pressed?

#

I am using animator in Unity for the animations

untold shore
burnt vapor
#

So you can define a dictionary with 2 generic types that indicate the type of the key, and the type of (in this case) the dialogue

untold shore
#

Huh. I need to look into that, that actually seems really useful!

burnt vapor
#
Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>();

// You can also fill it with lines from initialization
Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>()
{
  ["Dialogue1"] = "Hello, World!",
}

// Or add it later.
dialogues.Add("Dialogue1", "Hello, World!");
dialogues["Dialogue1"] = "Hello, World!";

Syntax might be a bit off here

#

Then you can just get it with dialogues["Dialogue1"]

#

There are additional checks to ensure a key exist:

if (dialogue.TryGetKey("Dialogue1", out var dialogue))
{
  // The dialogue exists
}
#

So you see it's easy. It's also very fast

#

Just make sure the keys are unique obviously

edgy tangle
#

If you’re pressed for time it might not be the best option right now , but in a past jam I did I liked the system we used, which was to have a dialogue queue defined in a ScriptableObject, with a UnityEvent field in each dialogue that would invoke when that line was finished. So you could then trigger different dialogue like a choice dialogue, or enable/disable objects, etc.

untold shore
#

Oooo ok. I still need to study it a little more (I promise you, im beginner beginner. This is my first coding game), but I really want to try it!

burnt vapor
#

Try it and see, it's super easy to use

#

Easier than fiddling with indexes probably

untold shore
edgy tangle
#

So like <string, string> means that you lookup a string by using a key as a string

#

Just a real dictionary. You need some block of text (the definition of the word), which you look up by the word itself

edgy tangle
#

It saves you from having to validate it more specifically

burnt vapor
# untold shore Most likely 😅 Quick question that I am confused about is the out var? On the a...

There are methods that start with Try. These are often, if not always, using what called the "Try Parse" pattern. The idea is that you attempt the action, and instead of returning the type as a result it returns a boolean indicating success. Any additionally returned information (such as the dialogue in this case) is returns in what's called "out parameters". These are explicitly keyworded with "out" to indicate they are set inside the method and will have a value when the method ends.

#

If the try method returns true, it can be assumed all parameters with "out" are set

#

This is the code behind the Dictionary. Note it explicitly has out defined, and therefore will set this variable before it ends.

#

Otherwise, it returns default(TValue), which is often just null

#

Also, is dictionary like a type?
Yes, almost everything in C# is. Maybe you mean the <string, DialogueType> part?

untold shore
#

Dude this is actually so cool! Trying it out right now.

timber tide
#

Dictionary best data struct

#
  • iterator
burnt vapor
#

The Try pattern can be found in many things. For example, int.TryParse attempts to parse its parameter (which is mostly a string) into an integer, and returns a boolean type indicating if it works

#

Theres also int.Parse which instead tries to parse, or throws an exception if it failed

untold shore
#

Nope, just didn't know where it would go honestly. So what could my dialogue type be? I have a dialogue script:

using UnityEngine;

[System.Serializable]
public class Dialogue
{
    public string OpponentName;
    [TextArea(3, 10)]
    public string[] sentences;
}

But thats only for the queue method. Would it be something else?

burnt vapor
#

So you see there's generally always an alternative that's not as graceful

timber tide
#

Only problem is you can't serialize dictionaries with unity :D

burnt vapor
#

Yeah, Unity doesn't support this natively. There are packages online that add support though

#

Not for the actual type, I believe. They add a new type similar to the Dictionary, but makes it serializable

hot wadi
#

Uh guys how do you make the character move? , im a beginner and dont rlly understand anything

burnt vapor
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

burnt vapor
#

Generally you'd use the character controller or a rigidbody for these things.

untold shore
# burnt vapor So you see there's generally always an alternative that's not as graceful

Quick thing if youre still here. Here's my code for trying it out:

    Dictionary<string, string> dialogues;
dialogues["WhoareYou"] = "The holder of certain parts of this universe, just as you.";
 public void DisplayNextSentencePostWin()
    {  
       
        if (WhoareYou == true)
        {
             sentencesaying = dialogues["WhoareYou"];
               StartCoroutine(TypeSentence(sentencesaying));
            ContinueButton.onClick.AddListener(EndDialoguePostWin);
            WhoareYou = false;
        }  

But now its giving me a null exception. Do I have to connect it to another gameobject?

burnt vapor
#

I might we wrong in saying the [""] = ""; type syntax adds the key if it doesn't exist. Use the Add method in that case

#

I thought it would

untold shore
#

Add method? How should I do that?

burnt vapor
#

See code above

rain ginkgo
#

Do anybody know if you can acheive the effect of a 3D model as a Canvas sprite in unity or did the person that made this game import png sprites for the inventory UIs?

burnt vapor
#

Not sure why it would throw this exception. I would expect a KeyNotFoundException

untold shore
#

Eh, wouldn't be surprised if it was my code sadly. Checking out to see if the Add works rq...

burnt vapor
#

By the way, note that a dictionary is case sensitive. If you check for the key "WhoAREyou" it would throw a exception.

#

This is something that can be disabled, if you don't want this

#

Dictionary<string, DialogueType> dialogues = new Dictionary<string, DialogueType>(StringComparer.OrdinalIgnoreCase);

#

Note the added StringComparer class

untold shore
#

Weirdly enough, its giving me the same thing: NullReferenceException: Object reference not set to an instance of an object
I just don't know what its trying to access though

burnt vapor
#

I would suggest you check if the key exists beforehand, then. If it still happens after it's not related to the Dictionary

untold shore
#

Its probably the key - Need to figure out how to add that

charred spoke
topaz mortar
#

I have this extremely simple setup.
A capsule that can move in 4 direction with a sword sprite as child that swings.
What's the best way to get the sword facing the other 3 directions when moving/facing those?

#

Also why does changing my player rotation to 180 rotate my tilemap?

timber tide
#

I can't imagine being able to rotate that 90 degrees if it's not a top-down 2D game

topaz mortar
#

it's a top down 2d

timber tide
#

If it's 2D you can just rotate with eulers usually. Don't have to worry about gimble or anything like that

#

you can actually use Quaternion AngleAxis too if you wanted if you specify z as up

topaz mortar
#

if (moveInput.x > 0) swordTransform.transform.eulerAngles = new Vector3(0, 0, 0); // Right
Isn't this a bit overkill?
Can't I just directly set the transform.z value?

timber tide
#

I dont think you can set independent values. Gotta make a new vector each time

dense pike
#

I need to create a money script so player van buy weapon off wall

topaz mortar
ruby python
#

Mornin all, been a while since I've been around here.

I'm having a bit of a struggle with a little simple 3rd person turret game idea. Idea is that the player controls a turret and has to shoot at paratroopers dropping to the floor 'downrange'. I'm using a raycast direction to control the rotation of the turret 'parts' but I'm struggling to get what I want from the vertical rotation.

I'd like for the turret's x rotation to be 0 if the mouse pointer goes below the halfway point of the screen but I can't seem to get my head around the maths involved.

#

This is the code I'm currently running

using UnityEngine;

public class TurretController : MonoBehaviour
{
    [SerializeField] Transform turretBase;
    [SerializeField] Transform turretPivot;
    [SerializeField] Camera mainCamera;
    [SerializeField] float rotationSpeed;
    // Update is called once per frame
    void Update()
    {

        Debug.Log(Input.mousePosition);
        //Debug.Log(Screen.width);

        Vector2 mousePositionOnScreen;
        mousePositionOnScreen = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

        Ray rayToWorld = mainCamera.ScreenPointToRay(mousePositionOnScreen);
        var aimAt = rayToWorld.direction;

        Quaternion newTurretBaseRotation = Quaternion.LookRotation(aimAt - turretBase.localPosition);
        newTurretBaseRotation.x = 0f;
        newTurretBaseRotation.z = 0f;

        Quaternion newTurretPivotRotation = Quaternion.LookRotation(aimAt - turretPivot.localPosition);
        newTurretPivotRotation.y = newTurretPivotRotation.y/2;
        newTurretPivotRotation.y = 0f;
        newTurretPivotRotation.z = 0f;

        turretBase.localRotation = Quaternion.Slerp(turretBase.localRotation, newTurretBaseRotation, Time.deltaTime * rotationSpeed);
        turretPivot.localRotation = Quaternion.Slerp(turretPivot.localRotation, newTurretPivotRotation, Time.deltaTime * rotationSpeed);
    }
}
#

Screen shot for reference. The white line is the screen.y halfway point.

proud escarp
#

Hello guys! Is that the right approach to delay the shooting? With awaiting Task.Delay? Or is there a better approach?

    private async void FireSingle()
    {
        Debug.Log("FireSingle");
        isShooting = true;

        Shoot();
        await Task.Delay((shootingDelayMilliseconds);
    }

    private async void FireBurst()
    {
        Debug.Log("FireBurst");
        isShooting = true;

        if (burstBulletLeft <= 0)
        {
            isShooting = false;
            return;
        }

        Shoot();

        if (burstBulletLeft < bulletsPerBurst)
        {
            await Task.Delay(shootingDelayMilliseconds );
        }

        burstBulletLeft--;

        FireBurst();
    }
stuck field
# rain ginkgo Do anybody know if you can acheive the effect of a 3D model as a Canvas sprite i...

Muck very cool game, anyway, to answer your question: You can use a camera as a viewport, take a picture using a render texture, and then load that based on the name of the object, it's probably best to not do this at runtime, unless required, as you can just match a texture2d to an item name or something for said pictures, but, reading the pixels of a render texture, then writing that to a file, saving it as a png, is how that could work

ruby python
stuck field
# proud escarp Hello guys! Is that the right approach to delay the shooting? With awaiting Task...

I don't think there's a "best approach" or even a better, but, some alternatives to look into if you don't like how you are doing it:

  • Use invoke with a time, it will delay the call until the delay is over,
  • A coroutine using yield return new WaitForSeconds(x);

I'd say your way is perfectly fine, there are alternatives, as with everything, you can look into them if you prefer them over your way

#

Invoke(Method, Seconds); I believe for invoke

proud escarp
# stuck field I don't think there's a "best approach" or even a better, but, some alternatives...

Thank you! It's more like I know C# because I work as a web developer in .NET environment, but completely new in Unity.. Sometimes I tend to use stuffs which I already know in C#, but there may be better approaches or more used pattern for these situations programming with Unity!
I tried the Invoke method but I was't able to make it work, because I made the methods recursive and the Invoke is not really waiting the end to fire again, so I might refactor a bit to use that.. I'll have a look to Coroutine which I have never used!

stuck field
grand snow
topaz mortar
#

What's a good way to keep track of how many monsters are in my scene so I can spawn more if some have died?

#

I'm thinking to use a reference list on my spawn script and just count the number of entries every few seconds?
If the referenced object is destroyed it's removed from the list as well right?

#

Or I could throw an event every time a monster dies to adjust a count somewhere

timber tide
#

singleton

#

event works, or just let the enemy do its own callback

topaz mortar
#

So I'd just have a singleton like MonsterCounter that keeps track of all the monsters?
Guess I can adjust it to include which scene the monsters are on

timber tide
#

GameManager works fine too if you want to keep it minimal

#

I say EnemyManager if you want to do something like object pool

timber tide
ruby python
timber tide
#

make the background plane very close to the turret

#

so the depth is smooth

#

probably better ways to handle it but I think that can work

ruby python
#

Yeah, but then you lose accuracy when shooting far off distance. lol. (I know, sorry, really not trying to be a pain. lol.). I'm going to try using a sphere collider somewhere 'middle' distance (I want the paratroopers to drop at different depths) that I think will work.

burnt vapor
#

The convenient thing about this is also that you're not hard tied to an interval. If for some reason you want some sort of cooldown, you could just decrement the value of _nextTick (or whatever you end up calling it) instead of extra steps to get it working
And also, if you had to tie a visual indication of the time left, you can just get the difference _nextTick - Time.time and use the result in some progress bar for example
And lastly, if it matters to you, this is very multiplayer friendly since you just need to inform users of the next timestamp in most cases.

#

Your approach also works. Alternatively a Coroutine also fits in here. There are no wrong paths with it really, but I personally had the best experience with Time.time

#
public class Example : MonoBehaviour
{
    private float? _nextBurstFireTick = null;
    private float _burstFireInterval = 0.1f;
    private bool IsBurstFiring => _nextBurstFireTick != null;

    void Update()
    {
        // Fire the next shot
        if (IsBurstFiring && Time.time > _nextBurstFireTick)
        {
            Fire();
            _nextBurstFireTick = Time.time + _burstFireInterval;

            // Additionally you'd increment some counter here to ensure we stop firing at some point.
            if (HasShotThreeTimes())
            {
                _nextBurstFireTick = null;
            }
            return;
        }

        // Start burst firing
        if (PressedFire())
        {
            Fire();
            _nextBurstFireTick = Time.time + _burstFireInterval;
        }
    }
}

Semi pseudo code, gets you an idea of how Time.time can very easily be included with a system so you can separate the burst firing logic

#

And yes, this is all copy pasted from a previous message

proud escarp
#

Thank you! Yes I will surely add a multiplayer later (very later on 🤣 ), I might give this Time.time a shot!

burnt vapor
#

Good luck! 😎

topaz mortar
#

Any simple way to detect if an object I would Instantiate would collide with another object before instantiating it?
For my monster spawner, so I don't spawn monsters (which collide with eachother) inside another monsters collider

#

Or should I use a simple workaround like force them to move away from the spawn point?

ruby python
#

I'm not sure how efficient it is tbh, but I've always used OnCollisionStay ( or OnTriggerStay) if true, move it, if not move on to the next thing.

timber tide
#

OverlapSphere/Circle

#

Trigger methods takes till the next fixed frame

topaz mortar
#

Ah, 30 minutes wasted on trying to figure out why Physics.OverlapSphere is not working, to then figure out I need Physics2D.OverlapCircle

tiny wind
#

how do I make it so that it loads the next scene on the build index? ignore the method name

keen dew
#

SceneManager.GetActiveScene().buildIndex + 1

tiny wind
#

ight thanxx

naive pawn
#

do you know what using is?

#

have you tried googling it

ivory bobcat
eternal falconBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

sterile radish
#

hi, im making an incremental game and im currently making the upgrades for it. how should i go on about making upgrades that do different things (i.e, one upgrade adds +1 to your click and another sends a robot out to do clicking for you)? is there a way to implement all of these possible behaviours into one central UpgradeItem script?

visual linden
# sterile radish hi, im making an incremental game and im currently making the upgrades for it. h...

I would try to think in abstractions. You want to be able to change what happens when you click, so that's some kind of "ClickBehavior", but you also want there to be a robot that can do the clicking for you, so this is some kind of "Clicker" system.. Normally, the Clicker is of type CursorClicker; and a CursorClicker is controlled by the user for manual clicking. Every time the CursorClicker calls Click(), it invokes the DefaultClickBehavior (adding a 1 to the score). At some point, the user upgrades their ClickBehavior to a BetterClickBehavior- Now, when their CursorClicker calls Click(), it invokes BetterClickBehavior which adds 2 to the score.
Then the user gets an upgrade that swaps out their CursorClicker for a RobotClicker; Now it's not controlled by the cursor any more, but by a robot that goes out and calls Click() on its own, invoking the current (or default) ClickBehavior every time.

You'd probably implement this with some kind of base class that has a type of IClicker and IClickBehavior. But architecturally there's a lot of room for how you set it up and what exactly you need for your game specifically.

ashen frigate
naive pawn
#

for knockback? why not a parabola?

#

parabolas define how things fall

ashen frigate
#

it doesnt look like it does parabola

#

ohhh wait maybe i need to y = x^2/2

naive pawn
#

wdym?

#

you'd want a parabola that opens downward, so y = -ax^2 for some a

#

but you don't need to actually have a parabola

trim gyro
#

where can I ask for help with unity's editor?

hexed terrace
trim gyro
#

thanks

hexed terrace
naive pawn
#

a parabola is just the shape an object traces under gravity, ignoring air resistance
so just simulate gravity and you'll get a parabola
@ashen frigate

ashen frigate
#

i need x^2/a and a needs to be a bigger number so it wil go up slower rn is shot up

sterile radish
frosty hound
#

Yes, you can do whatever you want.

#

The above example doesn't do any functionality, it's purely for organizing your data so that you can incorporate it into the logic and gameplay.

visual linden