#πŸ’»β”ƒcode-beginner

1 messages Β· Page 769 of 1

dusk jay
#

idk what they mean

#

but i think they arent the problem for things dissapearing are they?

naive pawn
#

they could be

#

errors can be a lot of things

#

if you don't know, then ask instead of ignoring

dusk jay
#

they were because of the sprinting code

#

i fixed them by removing it

naive pawn
#

doubt it

dusk jay
#

im now reopening my project

#

yeah no fix

naive pawn
#

yeah because that's unrelated

#

perhaps actually check the errors

#

send them here if you don't understand them

dusk jay
#

no those werent the problem i fixed the layout

#

now i can go back to the script

#

i was able to fix the problem

#

finally

#

looks like auto save wasnt saving my input so i just save manualy

slender nymph
#

but have you gotten visual studio configured

dusk jay
#

its working now

#

thx

swift sierra
#

Hello can anyone see what's wrong with my localization code, i'm trying with Tap {count} times but it keeps showing me the value I set in the editor and ignoring this. So I keep seeing 100 instead of 4 if I remove the value from the editor it fails straight away. withError parsing format string: Could not evaluate the selector "count" at 5

zenith cypress
#

Looks like it expects a dictionary as the arg

naive pawn
gloomy bison
#

mb meant to delete it :(

zenith cypress
#

I think if it is keyed in the string, it needs the dictionary, but if it is indexed it needs an array? It's a tad confusing at times for sure on the specifics.

naive pawn
naive pawn
#

but yeah i don't think a single integer is in the options

zenith cypress
#

If you did "potato: {0}" then you could just pass in the int for the arg, but with "potato: {Count}" you need either a dictionary or an object with that named field yeah. The reflection item on the left (under sources) shows the class one

naive pawn
#

but that second screenshot seems like they have variables set up separately, so im kinda confused on that

zenith cypress
#

Can even do xml, what in tarnation

hybrid cobalt
#

Hm, how can I make 2 separate game objects to communicate with each other (like Player to UI to update health)? I would normally use Signals in Godot, and Unity has Events, but not sure if people actually use Unity Events for this.

swift sierra
#

Thanks guys, I'm still a bit confused lol but I will give that dictionary example a shot as I might just need to add that second line with "Count", Count...that cant be right either πŸ€” . I think I may need to try and spend some more time in the docs

polar acorn
hybrid cobalt
#

Got it! Seems simple enough

timber tide
#

Unity has Unity Events which you can hook up in the editor, or c# events which you do from runtime binding

#

but too lazy for that and rather just direct reference when possible

#

usually the idea is those objects further down the hierarchy should have events to the parents if it does need to communicate back

#

But if communication is one-way (downward), it's proper to just direct reference if we're talking static elements

hybrid cobalt
#

Mhm, it should still be loosely coupled when using references

hot wadi
#

Events are typically one-way, no? I just think they save us from the nasty references when too many objects have to be triggered

grand snow
#

Thats the point of events, to allow anything to add a listener (or not)

#

the invoker of the event doesnt need to know about any listener

gloomy bison
#

hi. im trying to make a simple bus controller with wheels.
however, with no inputs the bus jumps out like so in image 1
code: https://pastebin.com/jdte5z5h
bus set-up - image 2
wheels - image 3 and 4
(the bus model is not mine if thats of importance)
if i've left any helpful information out, please let me know

#

but yeah please can i have a possible cause and possible fix for this? i'm not even sure why this is happening

maiden totem
#

I'm probably overcomplicating this to no end, but how would I check if the velocity of a rigidbody does not exceed the maximum speed in a certain direction? This is what I'm doing right now but I'm not sure if this is correct at all:

bool exceedsMaxVelocity = Vector2.Dot(playerRigidbody.linearVelocity, movementVector) / movementSpeed > 1;

playerRigidbody.linearVelocity += 
    exceedsMaxVelocity ?
    Vector3.zero :
    movementVector * (acceleration * Time.deltaTime);```
gloomy bison
#

i meant with no input. it just decides to shoot off whenever i press play

#

sorry, i should have specified

maiden totem
#

I hope this makes sense

#

I'm just trying to make a 3d rigidbody player controller that doesnt overwrite the velocity directly and doesnt add force

hot wadi
midnight tree
gloomy bison
eternal needle
gloomy bison
#

quick question about dictionaries, do i not need arrays if i'm using a dictionary?
example:

private void Start()
{
    peopleAndSeats = new Dictionary<GameObject, int>();
    peopleOnBus = new GameObject[64];
    seatNumbersTaken = new int[64];
}

void AddNewPerson(GameObject passanger)
{
    int seatNum = -1; // Default val -1

    for (int i = 0; i < seatNumbersTaken.Length; i++)
    {
        if (seatNumbersTaken[i] == 0)
        {
            seatNum = i;
            peopleAndSeats.Add(passanger, seatNum);
            peopleOnBus[seatNum] = passanger;
        }
    }
}
timber tide
#

You do not need an array, but c# has a special dictionary which includes a way to iterate over it via foreach

gloomy bison
#

ahhh thank you

timber tide
#

no guarantee on ordering

eternal needle
gloomy bison
#

tbf im not too fussed on ordering. if someone is in a seat, then it skips over it

gloomy bison
#

also does the key come first?

#

like the gameobject is the key

#

so it is

timber tide
#

you iterate by the key entry, yeah

#

if you want to iterate by unique values only*, you'd probably need to store those values into its own data struct

#

well, you iterate by kvp

gloomy bison
#

oki thanks

timber tide
#

meaning that you can come across the same value multiple times if multiple keys do point to it

maiden totem
#

so like if the player is pushed backwards with a speed higher than their maximum, they cant accelerate backwards but can slow down forwards

#

how would i do that?

eternal needle
# maiden totem how would i do that?

what you have is likely fine except the Vector2.Dot seems weird considering you're using vector3.zero later. If this is 3d then you should grab the specific values you want from the linearVelocity because otherwise I think you're comparing the xy values rather than xz which is horizontal movement.
If movement vector is always normalized then id assume this works fine. if the movement vector isn't normalized then comparing this to your movementSpeed is wrong
though still id really question if this case ever comes up in your game. Id just compare the .magnitude of the horizontal components of the linearVelocity to this movementSpeed

maiden totem
#

also ohh i see yeah, it should be vector3.dot instead

eternal needle
#

you need to normalize it anyways because you're using it for adding to the velocity

#

well actually i dont know if its normalized already. you can double check that pretty easily by printing out the magnitude

maiden totem
#

it is

#

its not 1,1 its sqrt(2),sqrt(2) when holding diagonally

#

so should be normalized

eternal needle
#

1/sqrt(2) or sqrt(2)/2 hopefully but yea

maiden totem
#

okay this seems to actually work quite well! needed to tweak the max speed/acceleration and linear damping values but it feels great

naive pawn
#

yeah sqrt(2) is about 1.414

zenith cypress
#

flow launcher is great for those quick math checks LUL

zenith cypress
rough granite
#

Oh, why

nova grove
#

I cant see my Serializedfield instances in inpector why?

soft stone
#
public class Laserbeam
{
    Vector3 pos, dir;
    Gameobject laserobj;
    LineRenderer laser;
    List<Vector3> laserIndices = new List<Vector3>();


    public LaserBeam(Vector3 pos, Vector3 dir, Material material)
    {
        this.laser = new LineRenderer();
        this.laserobj = new Gameobject();
        this.laserobj.name = "Laser beam";
        this.pos = pos;
        this.dir = dir;
        this.laser = this.laserobj.AddComponent(typeof(LineRenderer)) as LineRenderer;
        this.laser.startwidth = 0.1f;
        this.laser.endwidth = 0.1f;
        this.laser.startColor = Color.green;
        this.laser.endColor = Color.green;

        CastRay();

    }
    void CastRay(Vector3 pos, Vector3 dir, LineRenderer laser)
    {
        laserIndices.Add(pos);
    }
    void UpdateLaser()
    {
        int count = 0;
        laser.PositonCount = laserIndices.Count;
        foreach (Vector3 idx in laserIndices)
        {
            laser.Setposition(count, idx);
            count++;
        }
    }
}

I had a feeling that there's some problem when the objects / methods did not get coloured, Where could be the issue

I was following a yt tutorial on laser beams

naive pawn
#

as for the coloring, see below

#

!ide

radiant voidBOT
timber tide
nova grove
#

my classes are internal I think that is source of the problem @timber tide

timber tide
#

I would think it would throw any error here then, no? Unless you mean those are classes you've not serialized

nova grove
#

i tried asmdef for classes still not showing in inspector

timber tide
#

or just give me the class signature

nova grove
#

in sample it overrides like this I implement this to ```cs
using Player;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;

namespace Editor
{
[CustomEditor(typeof(PlayerTransform))]
class PlayerTransformEditor : UnityEditor.Editor
{
public override VisualElement CreateInspectorGUI()
{
var root = new VisualElement();
serializedObject.Update();
SerializedProperty property = serializedObject.GetIterator();
property.NextVisible(true);
while (property.NextVisible(false))
{
var propertyField = new PropertyField(property);
root.Add(propertyField);
}

        serializedObject.ApplyModifiedProperties();

        return root;
    }
}

}

timber tide
#

This looks more like a custom editor script and I assume it's just not being drawn then

radiant voidBOT
timber tide
#

Exclude the whole editor drawer and just get your classes shown in the inspector without it

nova grove
#

maybe Unity does not serialize fields of internal classes by default in the Inspector

timber tide
#

if the internal class is being used outside of the assembly, yeah, but I would expect some errors from either the IDE or after compiling.

gusty bone
#

!learn

radiant voidBOT
timber tide
#

unless the IDE isn't configured here

#

anyway, for the sake of testing just remove the internal keyword

dim egret
#

is there any way to remove the "is paused" bool on other scenes? alr so i have a scene called "game scene" and another called "pause scene" and when i press escape the pause screen overlaps the game scene and pauses it and that is when the "is paused" bool turns true, but the bool for the pause scene is set to false since it just loaded in so i wanted to know if theres any way to completely remove the "is paused" button for the pause scene without having to make a whole new script dedicated to it

#

like is there any way to set the bool to null (ik it prob doesnt) but like have an if statement that if the scene is called "pause scene" the bool gets rid of it

nova grove
midnight tree
dim egret
coarse wasp
#

If this isnt the right channel I can try a different place but I am having some trouble with shaders. I made an unlit shader in URP because I was following a tutorial. I realize now that unlit means no shadows which was dumb of me I should of thought of that. I do not want to have to try and write the shader again in shader graph because I frankly dont understand shader graph right now, is there an easy way to get basic shadows and lighting to work in my existing shader? I know in SRP you could have done #pragma surface surf Standard fullforwardshadows vertex:vert, but that doesn't work for URP

dim egret
#

like the pause action being disabled if the current scene is named "game scene"

midnight tree
slender nymph
#

that's not a bool being null, that's a Nullable<bool> allowing you to assign null

dim egret
#

should i just make a separeta script for it? but it would seem pointless to

midnight tree
brave robin
dim egret
#

i could send the whole script here. its not too long

brave robin
#

You could make an abstract scene change class, and then have two children: one for normal scenes, and one for the pause scene

#

Only the normal one can be paused and has the bool, and the other doesn't

dim egret
#
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

public class ChangeScene : MonoBehaviour
{
    [SerializeField] private InputActionReference pause;
    public bool isPaused;

    private void Start()
    {
        isPaused = false;
    }

    private void Update()
    {
        if (SceneManager.GetActiveScene().name != "Game Scene" || pause != null)
            pause.action.Enable();
        else
            pause.action.Disable();

        if (pause.action.WasPressedThisFrame())
        {
            PauseGame("PauseScene");
        }
    }

    public void ChangeLevelScene(string changeScene)
    {
        SceneManager.LoadScene(changeScene);
        Debug.Log("Changed scenes");
    }

    public void QuitGame()
    {
        Application.Quit();
    }

    public void PauseGame(string _pauseScreen)
    {
        isPaused = !isPaused;

        if (isPaused && !SceneManager.GetSceneByName(_pauseScreen).isLoaded)
        {
            Time.timeScale = 0f;
            Debug.Log("Paused");
            SceneManager.LoadSceneAsync(_pauseScreen, LoadSceneMode.Additive);
        }
        else if (!isPaused && SceneManager.GetSceneByName(_pauseScreen).isLoaded)
        {
            Time.timeScale = 1f;
            Debug.Log("Resumed");
            SceneManager.UnloadSceneAsync(_pauseScreen);
        }
    }
}
#

this is my code

#

messy ik

#

but if someone actually reads trough it pls tell me what i can improve on and learn to make this easier

#

i think imma make an abstract class, seems alot easier than.. whatever i made lol

slender nymph
spiral oracle
mild citrus
#

how do i fix this error

slender nymph
#

!ide πŸ‘‡ start by configuring vs code

radiant voidBOT
dim egret
#

or wait no

#

the pause script is just for pausing

#

nvm

rancid tinsel
#

guys this is a little stinky, is there something else I can do that's better?

#

the parameters on the Action are important for a different system

mild citrus
#

I configured it but now I have new errors it doesn't say how to fix

ivory bobcat
#

Maybe you meant to do something like... cs a = new A[4,5];

timber tide
#

but if this is like a small project then I wouldn't bother

rancid tinsel
#

why refactor?

timber tide
#

Well, you're asking if it's smelly and if you're not using any of the params there then that would be the answer. But, not that I've not* done similar before, but usually I keep it open-ended with passing a struct of data so even if I don't necessarily need it. It's still something that could potentially be useful later on in the project. Example: DeathInfo { KillSource, KillSourceLocation }

radiant voidBOT
slender nymph
rancid tinsel
polar acorn
timber tide
#

I usually dislike having to use them, but then I remember my input class is usually full of em

#

don't really care for the context most of the time

rancid tinsel
#

man the C#/Unity wizards have syntax for everything

#

thanks a lot guys

#

learned something new as always πŸ˜„

slender nymph
#

just make sure you also implement the first part of my message as well otherwise you are still not actually unsubscribing πŸ˜‰

spare saddle
#

Hey, I'm following a udemy tutorial on C# for Unity. I'm on a part for Input Events and what I'm trying to do is make it so when I hover my mouse over a cube game object it shows a debug saying "Over".

private void OnMouseOver()
{
Debug.Log("Over");
}

#

It doesn't work for whatever reason

#

when i hover my mouse over the cube.

valid violet
#

check if you put script on object if object have collider

spare saddle
#

The name of the script is InputEvents

valid violet
#

Did you run Play button to check if it is working in play mode? It should works.

polar acorn
spare saddle
#

I don't even know what a raycast is.

#

Well thanks for the info

mild citrus
polar acorn
mild citrus
polar acorn
mild citrus
polar acorn
#

If it's the same errors you showed before, and they're not highlighted, then you have not configured your IDE. Follow the instructions.

mild citrus
polar acorn
mild citrus
polar acorn
#

No one is allowed to help you until you configure your IDE. It's in the rules.

mild citrus
polar acorn
rugged beacon
rancid tinsel
#

I ended up replacing the parameters with discards, which fixes it... I think?

rugged beacon
#

idk but i believe it still a lambda you just discard the variable
you want a method or reference to it

slender nymph
#

that does not fix the fact you aren't unsubscribing

rancid tinsel
#

ah ok so I do need to pass a method to it

timber tide
#

you need to save is as a variable or make a whole new method

rancid tinsel
#

Like that, or is it still not counted as the same thing?

slender nymph
#

that's exactly the same as before

timber tide
#

I think you do need to specify the params on the methods right

slender nymph
#

if you want to use a method then your method needs to accept the parameters the delegate passes and subscribe directly with the method, not a lambda

rancid tinsel
slender nymph
#

for if you wanted to continue using the lambda

#

and you'd need to store the lambda in a variable then un/subscribe that variable instead of doing it with the lambda directly

rancid tinsel
#

wait so there is actually no way to ignore parameters from an event?

rugged beacon
#

you ignore it by not doing anything with it

rancid tinsel
#

well yes but I mean without having to pass them anywhere

#

I guess this doesn't really matter tho

slender nymph
#

the event is going to pass them no matter what

cosmic dagger
#

If you don't need them, don't pass them. If you need them, then pass them. You're not required to use the parameters . . .

slender nymph
#

even using the discard doesn't prevent it from passing the parameters, it just tells the compiler you don't want to actually use them

spare saddle
#

So what's the best way to learn how to code things in Unity as someone who's never coded before?

#

I can't seem to find any way to do it. I usually end up watching tutorials that end up being outdated

#

hence my previous coding problem

#

πŸ™

astral void
#

!learn

radiant voidBOT
astral void
#

probably this

zenith cypress
#

Not much will be outdated unless you are looking for a specific thing, like a Render Pipeline feature, or a very old Unity 5 tutorial LUL

bleak raft
#

Hi,
I'm doing a very simple school project where I've made a blackjack game and now need to make it multiplayer. The game is fully functional as single player. But how to make it multiplayer confuses me with how many different solutions I see out there.
Is there by any chance anyone willing to help me?

Thank you for your time and have a good day πŸ™‚

astral void
#

do you want it to be online multiplayer? if so, it is suddenly a very complicated project, and I wouldn't recommend it unless you already have a decent knowledge of unity and C# and are willing to learn a lot. for that, I would recommend making a post in #1390346492019212368 and ask there instead. If you want local multiplayer (not sure how that would work with blackjack) then it's far simpler.

kindred dome
#

if i have a script using InvokeRepeating to repeat a function every X seconds, what happens if i disable the gameobject that script is attached to?

#

does it stop repeating or does it keep going?

sour fulcrum
#

maybe not the answer you want but the best answer is to stop using invokerepeating

#

and use something like a coroutine which has better documentation and results online

wintry quarry
kindred dome
#

ive just realised a slight problem lmao

#

ive got an object disabling itself in a script and then that same script is to reenable it later

#

except its disabled so nothing happens

#

oop

kindred dome
#

is there a way to quickly delete all the points on a linerenderer?

sour fulcrum
#

if you set the array size to 0 iirc

acoustic birch
#

Could anyone teach me why unity allows code written like this?

CBUFFER_START (UnityPerMaterial)
    TEXTURE2D (_MainTex);
    SAMPLER (sampler_MainTex);
    float4 _MainTex_ST;
CBUFFER_END
keen dew
#

What do you mean "allows"? It's HLSL for making shaders

astral void
#

bc it's not c#? I assume that's what you're referring to

acoustic birch
#

"allows" means texture declaration is allowed in cbuffer declaration scope without error, which should be impossible

naive pawn
sour fulcrum
meager siren
#
using UnityEngine;
using UnityEngine.InputSystem;

public class DoorScript : MonoBehaviour
{
    public Transform mainCamera;
    public Transform player;
    public Transform door;
    public InputActionReference interact;
    public float openSpeed;
    public float closedSpeed;
    bool opened;
    RaycastHit hit;
    Vector3 currentRotation;
    Vector3 openTargetRotation = new Vector3(0, -135, 0);
    Vector3 closedTargetRotation = new Vector3(0, 0, 0);
    LayerMask layermask;

    void Start()
    {
        layermask = LayerMask.GetMask("Door");
    }

    void FixedUpdate()
    {
        currentRotation = transform.eulerAngles;
        if (Physics.Raycast(player.position, mainCamera.TransformDirection(Vector3.forward), out hit, 2, layermask))
        {
            Debug.DrawRay(player.position, mainCamera.TransformDirection(Vector3.forward) * 2f, Color.yellow);
            if (interact.action.IsPressed() && !opened)
            {
                opened = true;
            }
            else if (interact.action.IsPressed() && opened)
            {
                opened = false;
            }        
        }
        if (opened)
        {
            currentRotation.y = Mathf.LerpAngle(currentRotation.y, openTargetRotation.y, openSpeed * Time.deltaTime);
            transform.eulerAngles = currentRotation;
            if (transform.eulerAngles.y >= -120)
            {
                opened = false;
            }
        }
        if (!opened)
        {
            currentRotation.y = Mathf.LerpAngle(currentRotation.y, closedTargetRotation.y, closedSpeed * Time.deltaTime);
            transform.eulerAngles = currentRotation;
            if (transform.eulerAngles.y <= -15)
            {
                opened = true;
            }
        }
    }
}

(Watch the video for context)

weary finch
sour fulcrum
#

ill repost this over there

meager siren
naive pawn
#

why not just keep track of the state yourself?

#

ah, because it's wrong lerp

meager siren
#

wdym?

#

Should I be using a different lerp?

quartz shore
naive pawn
meager siren
quartz shore
#

omg ok something on steam

#

thank you

#

i will look into this

naive pawn
# meager siren Should I be using a different lerp?

"lerp" stands for "linear interpolation"
you're using it "wrong", in that you're giving different arguments that make it not a linear interpolation. it looks nice on the surface but has inconsistent and undesirable behavior once you get into the math

#

it'll technically never reach the openTargetRotation

meager siren
#

so how do fix it?

#

Well, make it wait till its done

naive pawn
#

you just.. wouldn't use it, tbh

meager siren
#

then what would I use?

naive pawn
#

but at least with that, you get consistent times

#

that solves one of the issues

#

for the asymtotic behavior, you could use an epsilon to snap

#

you might want to consider using a coroutine for this to make the logic much simpler

meager siren
#

coroutine?

#

ive already forgot about this

naive pawn
#

have you heard of those before?

meager siren
#

didnt the other guy explain that like last week?

naive pawn
#

no clue, i barely remember you

#

you'll have to search your message history for that lol

#

but coroutines basically let you have a contiguous block of code for logic that runs over time, rather than having a function called multiple times for each timestep

meager siren
naive pawn
#

don't remember that either.. i don't really remember people here

naive pawn
# naive pawn but coroutines basically let you have a contiguous block of code for logic that ...

for example, here's how you might do it with normal lerping (no smoothing)

IEnumerator Open() {
  float elapsedTime = 0;
  Vector3 rot = transform.eulerAngles;
  while (elapsedTime < openTime) {
    rot.y = Mathf.LerpAngle(closeAngle, openAngle, elapsedTime / openTime); // slerping quaternions might be something to consider too
    transform.eulerAngles = rot;
    elapsedTime += Time.deltaTime;
    yield return null;
  }
  opened = true;
}
meager siren
#

I love when I cannot understand code

#

makes me feel epic

naive pawn
#

that's normal tbh

#

coroutines definitely use stuff that you might not see in other game logic

#

there are probably guides/explanations online you can search for

meager siren
#

I see I see

#

yes understood

ivory bobcat
#

You could use an animation curve in conjunction with the third parameter if you want easing or some other functional rate of change.

naive pawn
#

oh that's also an option, forgot about that

#

you don't get asymtotic behavior with that

wicked galleon
#

Hiya im having an issue getting my button to work. I have a button with sprites attached to it and i want to be able to press the button and have an animation play for said button, but ive looked at tutorials and such and i dont get how their buttons just work with no "onClick" or anything like that so i would like some assistance please :)

naive pawn
wicked galleon
#

how would i go about that?

naive pawn
#

look in the button component in the inspector, there's an "on click" there - that's a unityevent rather than a message

#

click the plus icon and assign the component you have there, and set it to call OnClick

ivory bobcat
#
var button = new Button { text = "Click me" };
button.clicked += OnClick;```
wicked galleon
naive pawn
#

"On Click" kinda hints that it's the Unity UI one

ivory bobcat
#

Did you select a Button instance or prefab? The instance would have your instance members

naive pawn
ivory bobcat
wicked galleon
naive pawn
#

what's the component called

wicked galleon
#

like in the heirarchy?

#

then "Dice"

naive pawn
naive pawn
wicked galleon
naive pawn
#

it's the thing you put code in, the thing declared by class near the top of the file

wicked galleon
#

ohhhhh

#

well yeah "Dice"

naive pawn
wicked galleon
#

which one of these would allow me to call the method

naive pawn
#

the one that says onclick

#

the name of the method you created

sour fulcrum
#

(which is private btw)

naive pawn
#

shoot, do they need to be public? ive forgotten

sour fulcrum
#

i believe so πŸ˜”

wicked galleon
#

ah, ive made it public and its on the list!

#

thanks guys! πŸ‘

real thunder
#

the issue of firerate of a weapon depends on FPS really boggles me

#

so I made it that shooting is in a Fixed Update but I think that made cooldown quantifiable

#

so I have no idea how people do treat this issue in general, got any ideas?

midnight plover
#

firerate is not fps dependent per se, unless you code it that way

real thunder
#

yep, I meant basic solution with using Update and a timer of sorts

#

so yeah I would appreciate if anyone got an advice on how to make firerate framerate independent

midnight plover
#

what do you currently have?

real thunder
#

weird solution from my last project
player input is read at Update
shooting is at FixedUpdate on a timer
and a timer also makes into account how time steps not matching firerate and reducing time till next shot by that delta
there are bit more stuff bit it's not relevant I think

#

it works but I figure I might ask if there are better ways to do it

#

because what I did looks suspiciously overcomplicated

sour fulcrum
#

google has a lot of results when you search "unity frame independent timer"

wintry quarry
real thunder
#

iirc I failed to find a good solution so I made that

wintry quarry
#

If spawning projectiles it can place them at different positions based on the idea of calculating when in the intra-frame timing it should have spawned.

real thunder
#

that's like what I did but doesn't look overcomplicated, nice

real thunder
#

well it's nice to know I am on the right path, thanks

#

I would assume Unity got something premade for such things but yeah

sour fulcrum
#

Unity doesn't really pre-do that kinda stuff

#

it's too situational for how small it is i think

real thunder
#

meanwhile they got gimmicky stuff like smoothDeltaTime

sour fulcrum
#

That’s something where there’s not too many major ways people would want to implement that

wanton seal
#

im having an issue with my code. it's supposed to draw a raycast from the camera that follows the cursor. it does move according to the cursor, but it isnt drawn from the camera, just a random point in the scene. any ideas how i could fix/debug this?

hexed terrace
#

change that to cam.transform.position

wanton seal
#

okay, thank you

#

ill try it

hexed terrace
#

when you use transform in your code, that is accessing the transform for the gameObject that this component is on.

dusk jay
#

Hi, i was hoping to see if anyone would be able to spend some minutes teaching me how to make my enemie AI on my game

wanton seal
#

tysm its working now

hexed terrace
#

!ask

radiant voidBOT
# hexed terrace !ask

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πŸ”Žβ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.

-# For more posting guidelines, go to #πŸŒ±β”ƒstart-here

dusk jay
#

oh ok

#

thanks

wanton seal
#

okay, it draws it out from the camera, but its kind of weird

it shoots at a different angle than from what the camera is actually looking at

hexed terrace
wanton seal
#

no, i didnt. i completely forgot about the second one haha

#

i fixed it though

#

tysm for helping

keen cargo
#

hey yall, quick rigidbody related question.

so i had this issue of a player clipping through a corner with no effort, i've tried:

  • setting collision to the various amounts of Continuous collisions (continuous dynamic, continuous default, etc.)
  • made the colliders thicker
  • checked the physics collision settings (not that there was any point to that, the collisions WORK it's just that any corner is clippable)
  • made sure that i'm moving the character using the physics commands and not something like Transform
  • made sure that the physics controls are in FixedUpdate

This is the code that i ran before i tried another fix which worked out

Vector3 targetPos = rb.position + move * runSpeed * Time.fixedDeltaTime;
rb.MovePosition(targetPos)

This is the fix i did, that worked out

Vector3 targetVelocity = move * runSpeed;
rb.linearVelocity = targetVelocity;

though, i've seen many guides that still use MovePosition, am I missing something here? Because i wholeheartedly believe in using MovePosition instead, but for some reason it's just not working out for me

keen dew
#

MovePosition ignores colliders. It works in most cases because after MovePosition the physics engine detects that the player is inside a collider and pushes them out, but sometimes you get that kind of tunneling

#

MovePosition is mainly supposed to be used with kinematic rigidbodies only

keen cargo
keen dew
#

linearVelocity or AddForce are the safest ways to avoid that kind of edge cases, yes

#

If you want outside forces affect the player (punching etc) then AddForce is the easiest or you need to calculate the forces manually

keen cargo
#

yup got it, thanks

hallow badger
#

Am I the only one who is afraid to start Unity or any other game engine? Because it is important that you choose an engine that you believe in.

wintry quarry
keen cargo
#

Ofc for a single project you may need to stay on the engine for various reasons but there's nothing stopping you from using other engines

rough granite
#

Well that plus their lack of proper intellisense for using c# and poor documention for c#

grand snow
#

huh yea their code docs are a lil funny

timber tide
#

snakecase is superior

spare saddle
#

Can someone explain to me like I'm 5 what a raycast is? I still don't understand.

#

So It's a line that points from the gameobject towards a direction to detect whatever has hit it?

grand snow
#

fire out invisible line till it hits some physics collider

#

you can perform a raycast from any position you want and it can go in any direction you want for the distance you want

rough granite
spare saddle
#

But the game object is the origin?

slender nymph
#

it can be but doesn't have to be

#

you specify the origin and direction when calling the Raycast method

spare saddle
#

So what exactly would raycasts be useful for? I assume menu buttons?

rough granite
#

A many of things one common one is checking if you are grounded

grand snow
#

well ui interaction is done for us by unity

#

or if a gun firing some bullet hit anything

slender nymph
grand snow
#

(often known as hit scan by players)

spare saddle
rough granite
grand snow
#

hmm im not sure, a physics sweep is also instant so

#

maybe someone else knows

timber tide
#

I choose the one not to squint at

grand snow
#

rust uses snake case but c# already has a set standard so lets stick to that

slender nymph
timber tide
#

I just use standard, but I get to the point where adding more than 3 variables syllables to my class names halts my progress lol

ivory bobcat
# timber tide DbContextOptionsSqlServerExtensions vs Db_context_options_sql_server_extensions

Coming from C, snake case reminds me of macro definitions. For me, the underscore often blends in with white space when having to look at multiple lines (50+) of declarations that have got similar names.cs foo_bar_baz qux_quux_quuz; foo_bar baz_qux_quux_quuz; foo_bar_baz_qux_quux quuz; foo bar_baz_qux_quux_quuz; foo_bar_baz_qux quux_quuz;Bad naming convention and non consistent patterns are the true villains though.

tired python
#
using UnityEngine;
using UnityEngine.InputSystem;

public class mouseScript : MonoBehaviour
{
    Ray ray;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 mouse_pos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
        ray = new Ray(mouse_pos, new Vector3(0.0f, 0.0f, 1.0f));
        CheckForColliders();
        Debug.DrawRay(ray.origin, ray.direction, Color.red);
    }
    void CheckForColliders()
    {
        Debug.Log($"{ray}");
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Debug.Log(hit.collider.gameObject.name + "was hit!");
        }
    }
}

i have this script attached to main camera and i don't really understand why it's not recognising hits onto colliders

wintry quarry
tired python
#

oh wait nvm, they don't have any collider on them, the ducks...

wintry quarry
#

But your code is doing a 3D raycast

#

And yeah - you will definitely need colliders. Just make sure you're using the right kind of raycasts (2d or 3d)

#

Also if you're trying to detect mouse clicks here I would recommend either:

  • Using the event system for this instead, e.g. IPointerEnterHandler/IPointerDownHandler
  • Using Physics2D.GetRayIntersection instead of Raycast
tired python
#

2d is basically 3d without one dimension, since my directional vector is 0.0f, 0.0f, 1.0f, doesn't that basically do the job?

#

i just wanna know whether my mouse is on a collider or not...

wintry quarry
tired python
#

O_O

tired python
#

raycasts use physics engines...why?

wintry quarry
#

you're using Physics.Raycast

#

that's clearly part of the physics engine

ivory bobcat
grand snow
rough granite
wintry quarry
#

OnMouseOver doesn't work with the new input system

#

that's why I recommended IPointerEnterHandler/IPointerExitHandler

rough granite
wintry quarry
# rough granite Really? Didn't know though i also havent touvhed the new input system yet

Yep, check the docs you linked:

Note: New projects created with this version of Unity are pre-configured to use a version of the Input System that doesn't support this callback. To support this callback in your project, you can change the Active Input Handling setting in Player settings to either Both or Input Manager (Old). However, doing so is not recommended as the legacy Input Manager is nearing the end of support and Input System is the recommended solution for new projects. For more information, refer to Migrating from the old Input Manager.

tired python
#

wait a second, how would you make a ray go into the screen without using the Z coordinates O_O

wintry quarry
#

Using Physics2D.GetRayIntersection instead of Raycast

tired python
#

ohh

#

lemme check

wintry quarry
#

And nobody says not to use the z coordinate

#

you should be using Camera.main.ScreenPointToRay(Mouse.current.position.value) to create the ray

tired python
#

ahh shiii, now i gotta go find camera documentation instead of physics for raycast

#

what

#

am i doing it in a dumb fashion or smth? is this not how you guys get to know about methods you didn't know a type had or smth?

wintry quarry
#
Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.value);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, distance, layermask);```
#

well you said "instead of physics" so I thought you were getting confused about the fact that you need both of these things together

tired python
#

ahh ok

tired python
#

the documentation has nothing related to exactly what the integer is gonna be though

wintry quarry
cosmic dagger
wintry quarry
#

yes that's the one that returns RaycastHit2D (that you just deleted)

tired python
#

sry, some sort of bug happened and the msg i wanted to upload didn't happen, that's besides the point. what is the int gonna be? there's no range nothing

wintry quarry
#

"The number of RaycastHit2D results returned"

#

that version of the function is for getting multiple raycast hits

#

you want the one that just returns a single one

#

which, like I said, is there if you scroll down. You posted a screenshot of it a second ago

tired python
#

ya, i got that

wintry quarry
#

just use that one

tired python
#

does this mean that if it were to hit 2 or 3 colliders, it would return 2 or 3

grand snow
#

sometimes we want to do a raycast and get the first thing hit
other times we want everything that the ray hit on its path

wintry quarry
#

If you look at the parameters there's a results parameter which is where the RaycastHit2D results actually get put into

#

the return value just tells you how many it put in the list

tired python
wintry quarry
grand snow
#

you have options you can PICK

#

read the docs for more than 2 seconds

polar acorn
tired python
#

ok i think i got it, so... if i am not wrong, the RaycastHit2D returned has info regarding the collider it hit which i can access using its various properties

wintry quarry
#

correct

#

Assuming it actually hit anything

toxic trench
#

whats the state on Unity and multithreading support?

#

last time i checked was almost null

teal viper
grand snow
#

There are more things can be done/used in unity c# jobs
And ECS has good support for using jobs

toxic trench
#

most shit isnt thread safe, i dont mind doing my own synchronization points, but unity seems to be checking and preventing to use api code on non main thread

teal viper
#

Most api is main thread bound, but it's rarely the actual bottleneck anyway. And there are reasons for it to be main thread bound. Most engines have such limitations. For example, unreal engine.

minor quiver
#

is there a chance anyone can help me with this bug? i have no idea why its happening and have been trying to fix it for about two weeks now

hexed terrace
minor quiver
#

not even sure i should be asking here so if i can ask somewhere else do tell me

teal viper
minor quiver
#

and when i comment it out its the other one

teal viper
wintry quarry
hexed terrace
wintry quarry
#

Because your instance is probably being assigned in that class in Awake, which is running after this

strange lintel
#

need help these always appear:

MissingReferenceException: The variable m_Targets of GameObjectInspector doesn't exist anymore.
You probably need to reassign the m_Targets variable of the 'GameObjectInspector' script in the inspector. Parameter name: componentOrGameObject
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <7b8172fcdd864e17924794813da71712>:0)
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <7b8172fcdd864e17924794813da71712>:0)
UnityEditor.PrefabUtility.IsPartOfVariantPrefab (UnityEngine.Object componentOrGameObject) (at <8081513dc2364383b8289d30d2169b2e>:0)
UnityEditor.GameObjectInspector.OnEnable () (at <8081513dc2364383b8289d30d2169b2e>:0)

minor quiver
#

i also thought it might be smth with what runs first but wasnt sure how to test it

hexed terrace
#

dont enable the gameobject with this code on before the eventmanager

minor quiver
#

what

#

wait ill send the event manager might help

teal viper
minor quiver
#

this is the even manager im using

hexed terrace
minor quiver
#

just making an instance of the dialogue events

minor quiver
wintry quarry
grand snow
wintry quarry
#

another way is a lazy-assigned Instance property for the singleton (but this can be slower)

minor quiver
grand snow
#

Its not throwing an exception, its just logging an error

#

so code execution continues

#

if you actually threw an exception there it would return early

minor quiver
#

but the game just stops running doesnt that stop the code?

grand snow
#

sorry, why do you think the game stops running?

minor quiver
#

or rather its paused

grand snow
#

unity pausing on errors is just to aid in debugging and is an editor only feature

minor quiver
#

do you mean its a good coding principle in general?

grand snow
#

i dont know what you are on about πŸ˜†

#

logging text does not affect execution

minor quiver
#

me neitherπŸ˜‚

minor quiver
naive pawn
#

that isn't an error

#

that is logging text in the error format

grand snow
#
Debug.LogError("I don't stop anything!");
File.Delete("C:/"); //ohh no!
minor quiver
#

sure but it works the same way in unity doesnt it

naive pawn
#

it does not

grand snow
#

^ read and learn

naive pawn
#

compare these

Debug.LogError("Error-formatted log");
Debug.Log("After LogError");
``````cs
throw new Exception("Thrown error");
Debug.Log("After throw");
minor quiver
naive pawn
#

i don't mean to insult or anything, but

sure but it works the same way in unity doesnt it
my man you are arguing against us

grand snow
#

i said this already so i want to get over the most important point 😐

hexed terrace
#

saying "read and learn" is not anything mean .

grand snow
#

coding is hard and confusing so reading the lang documentation is the best way to learn

naive pawn
#

you have a false assumption, and that's a pretty normal/human thing to do

what's important is that you can discard that assumption when you have reason to believe it's wrong - for example, someone more experienced tells you that the assumption is wrong #πŸ’»β”ƒcode-beginner message

minor quiver
#

thats not even what i have a problem with though...

#

i meant the debug log thing

naive pawn
#

what about it?

#

the singleton needs to be initialized before other stuff can use it

#

there are multiple ways to achieve that, carwash gave one of them

minor quiver
#

should i make my object inherit from monobehaviour then instead of making it with the even manager?

#

im very confused here

naive pawn
#

...huh?

#

which object are you referring to here

#

you shouldn't have anything inheriting from eventmanager

hexed terrace
minor quiver
rocky canyon
naive pawn
#

im not a pillar of gamedev, ive no way to know if that's standard/common lol

naive pawn
#

it's certainly a way to do it

hexed terrace
#

script execution order can quickly get out of hand.
having a while loop in Update sounds like a poor / lazy way to do it.

rocky canyon
#
    private void TryAssignInteract()
    {
        var inputManager = Object.FindFirstObjectByType<InputManager>();
        if (inputManager == null)
        {
            Debug.LogWarning("[InteractRaycast] No InputManager found in scene.");
            return;
        }

        var actionRef = inputManager.GetAction("Interact");
        if (actionRef != null)
            AssignInteract(actionRef);
    }``` ie
naive pawn
minor quiver
#

it just doesnt inherit from anything

naive pawn
#

how's it getting, "activated" per se then?

minor quiver
#

cause im creating it in events manager

naive pawn
#

is something else calling initializing/calling methods on it?

rocky canyon
naive pawn
#

ah, i see.

hexed terrace
rocky canyon
#

yea, i guess ur right

naive pawn
rocky canyon
#

i was just being lazy lmao to be honest

#

i had thought of making another manager but thought i could find a cheeky way

minor quiver
naive pawn
#

@minor quiver ok, so DialogueEvents doesn't really matter here. what does matter is whatever class is trying to access the EventsManager.Instance, which would be.. whatever class this is #πŸ’»β”ƒcode-beginner message

minor quiver
#

but it says that i havent set a reference to it

hexed terrace
naive pawn
minor quiver
#

and how do i get around that?

hexed terrace
#

Share the full error, so we can see the stack

naive pawn
minor quiver
hexed terrace
minor quiver
naive pawn
#

ok, then ask instead of pretending the message doesn't exist

minor quiver
naive pawn
#

(we aren't psychic - we won't know if you understand or don't understand if you never say anything)

minor quiver
naive pawn
minor quiver
#

the only thing from what you told me that i know so far is singleton

naive pawn
minor quiver
naive pawn
#

carwash elaborated here

#πŸ’»β”ƒcode-beginner message
is there any terminology or wording there you don't understand?
if/once you understand each term on its own, do you understand it as a whole? (don't worry about the code yet, just work on understanding the concepts for now)

naive pawn
rocky canyon
#
    private IEnumerator SubscribeWhenReady()
    {
        while (TickManager.Instance == null)
            yield return null;

        fastTick = TickManager.Instance.AddTick("FastTick", 0.25f);
        slowTick = TickManager.Instance.AddTick("SlowTick", 3f);

        fastTick.AddListener(OnFastTick);
        slowTick.AddListener(OnSlowTick);
    }``` crap... i've found i do it many different places.. 
time to actually sit down and restructure my setup
-# #hooray
minor quiver
#

or did i understand it wrong?

naive pawn
#

that would be one way to do it

rocky canyon
#

the basic understanding is there yes..

naive pawn
#

it's not the only way, but you're on the right track

rocky canyon
#

the thing ur calling methods from must be a thing before the other thing is a thing

minor quiver
#

does just enabling a disabling items in unity work in a way that helps me with this

#

so like can i just enable and disable it from the editor or smth?

rocky canyon
#

ya, when u enable a script its OnEnable() and Awake() run.

#

ohh from the editor? well thats a hacky way.. that wouldnt happen in the game

#

woudlnt help u in the long run

naive pawn
#

if you disable (or deactivate) stuff outside of playmode, they'll start as disabled/deactivated when you enter playmode, and then you would have some process to enable/activate them

minor quiver
naive pawn
#

Awake first

minor quiver
naive pawn
#

it's not all awakes first

minor quiver
#

cause im making the thing in awake and then calling it OnEnable

hexed terrace
#

Awake is only called before OnEnable within the context of a single script. If you have multiple scripts with these methods, both Awake and OnEnable can get called for one script, before both get called for another one.

Start is always called after Awake and OnEnable for all scripts

naive pawn
#

i shouldve been clearer, that's on me - Awake is before OnEnable for each gameobject

rocky canyon
#

use logs to visualize when things happen
if you put a log w/ the name of the script in the Awakes() OnEnables() etc.. u can see in the console which calls when

naive pawn
#

right now you have them on different gameobjects, so there's no guarantee that Awake on one will be called before OnEnable of another

minor quiver
rocky canyon
#

good luck πŸ€

forest wolf
#

Yeah, if I have this problem usually I move the dependency to Start rather than Awake, then if I still have problem there is a script execution order you can adjust

rocky canyon
#

last resort imo

#

like carwash said.. it gets messy and out of hand quickly

#

especially if thats your go-to solution

hexed terrace
#

Using Start() to register delegates/ actions generally isn't great .. especially if you're going to be enabling/disabling the object.

rocky canyon
#

i've done it before for GameManagers and stuff.. (things that are persistent thru the whole game) nothing wrong with having them have priority in the execution order

minor quiver
#

i think start wokred but it looks weird in the code now cause im unsubscribing from it OnDisable

rocky canyon
#

whats wrong with that? thats where i unsub from everything

minor quiver
hexed terrace
#

!code

radiant voidBOT
minor quiver
#

might be easyer than screenshots

hexed terrace
#

☝️ inline code section

forest wolf
#

Oh we are talking here about delegates? I missed that part, sorry. Then yeah it's better to do that OnDisable and unregister OnDisable to be sure you don't call the method on the inactive instances

rocky canyon
minor quiver
#
code test

hexed terrace
#

the tilde key.. the thing you'd use for bring up a console in games

minor quiver
#

found it

#
using UnityEngine;
public class DialogueManager : MonoBehaviour
{

    private bool dialoguePlaying = false;
    
    private void Start()
    {
        EventsManager.Instance.dialogueEvents.onEnterDialogue += EnterDialogue;
    }

    private void OnDisable()
    {
        EventsManager.Instance.dialogueEvents.onEnterDialogue -= EnterDialogue;
    }
#

im doing this now

rocky canyon
#

aye.. look at you.. leveling up πŸ’ͺ

timber tide
#

Usually I just delegate from the manager on instantiation and let the manager handle it all, but delegating in start implies a singleton and I know people are iffy about that

minor quiver
#

and seems to be working i think

hexed terrace
minor quiver
#

i both spawn and call it while playing

hexed terrace
#

if you are, then it will not work the second time you enable it

rocky canyon
#

lol.. had trouble finding the script execution order page on the docs 🀣
they changed it.. or added more documentation or im just ignorant
i remembered it being the first result.. but meh, small potatos

minor quiver
#

wait let me test it

hexed terrace
#

you just said you think you are... so.. go make sure

rocky canyon
#

|| dont assume anything ||

naive pawn
rocky canyon
#

drunk dash

hexed terrace
#

it's (often) on the same key as the tilde.

forest wolf
rocky canyon
#

so far it works..

#

but thats why i asked here.. b/c i was worried it wouldnt

minor quiver
#

im never exiting the dialogue cause i couldnt test it up until now with that bug so for now no problems

rocky canyon
#

so for that use-case its fine i believe

minor quiver
#

i would like to know if you have any better ways to fix it than start()

rocky canyon
#

(1 extra if logic that it runs in Update) <- only downside i see

minor quiver
#

cause i do plan on exiting at some point

naive pawn
hexed terrace
minor quiver
naive pawn
#

which part exactly?

minor quiver
#

does it let me activate an object first before another

naive pawn
#

you never answered my question for clarification

forest wolf
#

So isn't the 'OnEnable' and 'OnDisable' problem only at the scene start when not all objects have yet been instantiated? In that case adjusting the execution order should fix the issue, right? Or am I missing something?

naive pawn
#

you generally shouldn't overuse SEO

minor quiver
#

as a concept but i have no idea how to code it

minor quiver
hexed terrace
# minor quiver i have no idea what it is though

I don't understand what you don't understand. I can't get in the beginners head ..

it's simple.

EventManger is active in the scene.
DialogueManager is not active in the scene.

EventManager initialises.
Now at some point you need to have something to enable the game object with DialogueManager on.

naive pawn
naive pawn
# minor quiver SEO?

script execution order (may also refer to search engine optimization in other contexts)

minor quiver
#

i have like one idea on how to do it

hexed terrace
#

In a game I'm developing I have a manager that just has a list in.
I ittirate over the list and enable the assigned gameobjects in the order

solemn crypt
#

Is there any code that allows us to improve fps ?

minor quiver
hexed terrace
#

having it as a list just makes it more robust because you don't need to add any more code if /when you want to add more to the list

forest wolf
naive pawn
#

to be honest, im kind of parroting advice here - i haven't had much reason to use SEO to begin with.

from my own viewpoint (take with a grain of salt, since i haven't used it) it's kind of an external thing to the rest of your codebase, and it's somewhat opaque and may break subtly if you make a mistake with it. putting dependencies in code makes it easier to visualize or modify

cold bolt
#

how to make a car climb steep slopes but at the same time it wasn't too fast, I'm just trying to make a game with an off-road vehicle?

forest wolf
solemn crypt
#

Any ideas as to why my fps would be tanking I’ve put out 2 demos and it seems to be an issue with the game

hexed terrace
solemn crypt
#

Ok πŸ‘

tired python
#

is this LayerMask layer = LayerMask.GetMask("Enemies"); supposed to be this or this

naive pawn
#

also, you can serialize LayerMasks to avoid magic strings

#

(the resulting dropdown should make it obvious which one it's referring to πŸ˜‰)

tired python
#

that's a great idea, btw what do you mean by magic strings?

#

seamingly unknown code which doesn't explain itself?

naive pawn
#

hardcoding strings that are specific things

#

specifically the "Enemies" string in this case

#

other examples would include animator parameter names or resource names or gameobject names

tired python
#

i thought it was self-explanatory but oh well...

naive pawn
#

they're things that would break if you made a typo or renamed something (without changing all the corresponding strings), and since they're strings instead of identifiers, IDEs can't really help check with static analysis or rename symbol refactors

#

similar concept is magic numbers, hardcoded numbers that mean specific things

hybrid cobalt
#

Im trying to use Unity Events to make the Player's health make the Health Bar update...but, how can I pass data through a Unity Event?

I want to pass the health_amount through the event.

naive pawn
#

unityevents have generics, so like, UnityEvent<int> for one that passes an int

hybrid cobalt
#

I tried doing this:

public class Player : MonoBehaviour
{
    public float health = 10;
    public UnityEvent<float> onHealthChanged;

    void Damage()
    {
        health -= 1;
        onHealthChanged.Invoke(health);
...

But when I try to connect the signal in the inspector, it asks me to set a value:

wintry quarry
#

not the Static Parameter list

#

(in the dropdown)

hybrid cobalt
#

This right?

#

Yea! Now it works, thanks !

wintry quarry
#

yes

tired python
#

aight, the thing is working now. any ideas as to what i need to look into so as to create a temporary object at my mouse position when the user clicks on the unit they wanna deploy?

wintry quarry
gloomy bison
#

hi. me again.
i have a time thats supposed to count down from 5 to 0 but stop if the bus is no longer in the selected zone. imma make it so the user has to hold down the brake too later.
my issue:
the timer goes instantly from 5 to 0 as shown in the video. why is this?
code:

 private void OnTriggerEnter(Collider other)
 {
     Debug.Log(other.name);
     if (other.CompareTag("Bus"))
     {
         Debug.Log("Boarding...");
         isIn = true;
         while (timer >= 0 && isIn)
         {
             timer -= Time.deltaTime;
             Debug.Log($"{timer} {isIn}");
         }
         if(timer <= 0)
         {
             foreach(var p in peopleInQueue)
             {
                 BusManager.SeatMe(p);
                 Debug.Log("Boarded");
             }
         }
     }
 }
wintry quarry
#

the whole idea of having a loop in here makes no sense

#

your entire loop is, of course, running instantly

gloomy bison
#

oh so should i make a method for it?

peak umbra
#

Hello

#

Admen

wintry quarry
peak umbra
#

Admin unity

gloomy bison
wintry quarry
#

FixedUpdate is implicitly in a loop

#

over time

gloomy bison
#

so an if statement instead of a loop?

wintry quarry
#

yes

naive pawn
#

in that case you could also just use the timer do double duty as the state too rather than a separate bool

gloomy bison
#

ahh understood. i will have a play. thanks

gloomy bison
#

like this:

 private void FixedUpdate()
 {
     if (timer > 0)
     {
         timer -= Time.deltaTime;
         Debug.Log($"{timer} {isIn}");
     }else
     {
         foreach (var p in peopleInQueue)
         {
             BusManager.SeatMe(p);
             Debug.Log("Boarded");
         }
     }
 }
private void OnTriggerEnter(Collider other)
{
    Debug.Log(other.name);
    if (other.CompareTag("Bus"))
    {
        Debug.Log("Boarding...");
        isIn = true;
       
    }
}
#

right got it. thank you!

naive pawn
gloomy bison
#

ah yes

tired python
wintry quarry
#

In fact it's definitely null

#

because it's private and you never assigned it to anything

tired python
# wintry quarry `spriteToRender` may be null

i mean yeah, but then that doesn't make sense as to why its popping
NullReferenceException: Object reference not set to an instance of an object mouseScript.Update () (at Assets/Scripts/mouseScript.cs:27) this msg

wintry quarry
#

it's null

#

and you're trying to dereference it

#

that's precisely what a NullReferenceException is

grand snow
#

Agreed

tired python
#

didn't i do this though spriteToRender.sprite = Droplet;

wintry quarry
#

because spriteToRender itself is null

#

you have to assign that reference (spriteToRender) before you can use it

#

Also spriteToRender is not a good name for that variable. It's a SpriteRenderer, not a Sprite

tired python
#

aiaiaia

#

so, i need to go into unity and assign it the Sprite Renderer component by first setting it's modifier as [SerializedField]

wintry quarry
#

Yes that would be one way to assign the reference

tired python
#

hell yeah, i understand ur language

grand snow
#

Understanding null reference exceptions complete! ⭐

rough granite
grand snow
#

Once you know what it really means you can better debug and fix them

tired python
#

i clicked on it

#

and this happened

rough granite
#

Is this intended?

tired python
#

i wanna drag and drop those units onto the game screen

rough granite
tired python
grand snow
#

Experience!

naive pawn
#

if you're working in 2d you generally shouldn't touch Z positions, and work with Vector2s

rough granite
naive pawn
#

the camera should usually be at Z -10

tired python
tired python
hot wadi
#

Use vector2 instead

tired python
#

oh wait, i think i got it? spriteToRender.transform.position = mouse_pos;

tired python
hot wadi
#

You are setting the mouse_pos as Vector3, which includes the z axis. Technically it moves ur object close to the screen

rough granite
tired python
#

i could reference to some other object in the heirarchy...

naive pawn
#

yeah no, there is some deep misunderstanding there

rough granite
#

Since right now when you move that sprite renderer to move position it moves the camera object as a whole there

tired python
naive pawn
#

you need some separation of concerns there

rough granite
naive pawn
#

what is spriteToRender even for if it's just on the camera

#

are you just storing the sprite there for some reason

#

if that's the case, you could just store the sprite itself

hot wadi
#

The transform.position of any component is the transform of the game object it’s attached to

#

U are trying to move the camera itself

tired python
#

so...i currently have the above attached scripts working in tandem. i remember thinking that when i wanted to build a way so that the mouse could drag and drop stuff, delete tower and stuff, upgrade towers (maybe)...that i would need to attach it to something completely unrelated to the gameobjects which have sprites and other stuff on them. so i attached it to camera. Now that, the mousescript finally recognises when i click on the deploymentUI, i want it to load up the sprite which the mouse is clicking on too, that's why, i attached a sprite onto it.

#

now, in order for the sprite to show up at the mouse's location, i am trying to change its position...that's why i initially used transform.position, not realising that that would change the gameobject the sprite renderer is attached to

hot wadi
#

U should treat the draggable sprites as separated objects

tired python
hot wadi
#

So what I understand here is that u want a tower defense system with draggable sprites that will spawn the associated objects like towers, turrets .etc.

#

It’s like packing a candy. U have the wrap as the sprite, the candy inside is the associated objects. They together form a completed object. And u can easily reference connected parts in the script with prefabs and components,…

hot wadi
#

Yeah sure, why not

#

I’m having a hard time trying to understand ur thinking process

tired python
#

@hot wadi

#

i realised, i don't need three if blocks, just two will do with a nested if-else logic

hot wadi
#

So it’s like a customized cursor

tired python
#

at the end of this, i want the cursor to just manage loading up sprites and deleting them on the game screen

hot wadi
#

Ok, what if u need different sprites for different objects? U are gonna reference them all in the camera script?

tired python
#

is this a bad way of doing it

hot wadi
#

Then how are u gonna check what object gets to assign what sprite on the cursor?

tired python
#

no object assigns anything...

#

i check the tags, match em with a sprite, then make sprite rederer's sprite become that sprite

naive pawn
#

you could skip that second step by just having each thing provide the sprite directly

tired python
#

what do you mean by each thing

naive pawn
#

the things you're clicking

#

instead of hardcoding each unit with a tag, have a component to supply the data

#

you could even have an SO that when you assign to the component it sets the spriterenderer of the button automatically too

hot wadi
tired python
#

so just...put the sprite i clicked on, onto the sprite renderer....using the gameObject returned by raycastintersectoin?

tired python
hot wadi
#

Set them on different layers and let the raycast pick the droplet’s layer only

naive pawn
#

what are you actually raycasting for? a collider, no?

tired python
#

the ray won't hit the droplet though, cus if the droplet hits the black area, the droplet ain't hit

#

both the box and the droplet have a collider

naive pawn
#

whatever gameobject has the collider will be responsible for providing the info via a component

naive pawn
#

that definitely doesn't need to be a thing

tired python
#

suppose box does not have a collider, then when the mouse clicks on the black area, the ray hits nothing.

hot wadi
#

I just realized that u use collider on a UI object

tired python
#

i mean...how else would i know whether the mouse is or isn't on the ui object though

naive pawn
naive pawn
tired python
naive pawn
#

that's my point

tired python
#

then how do i get a reference to the droplet though

#

unitOneBackGround is the square in question and UIDroplet is the droplet

#

unitOneBackGround doesn't have the droplet sprite attached to it

#

so if ray does hit it, what the RaycastHit2D references ain't the droplet sprite, it's the square sprite

naive pawn
#

hold a sprite or hold a spriterenderer

#

pretty straightforward

tired python
#

ya but like, how do i get the reference to the droplet, not the square

naive pawn
#

have you like. never dragged components around before

#

make a new component as the thing managing the clicks (replacing the tag check)
that component would have a sprite/spriterenderer field (choose one)
if sprite, drag the sprite you want to use as the preview into that field
if spriterenderer, drag the child object that has that sprite into that field

tired python
#

so...i attach a new script to it, and reference the droplet into its [SerialiseField] sprite renderer

hot wadi
#

The easiest way is to have a script attached to the yellow box with a SpriteRenderer reference and the collider or however u use to make it detectable , then u can drag the Droplet reference in that box

tired python
#

on god, that's a clever way to do it

#

no tag checks hurray!!

hot wadi
#

Btw u have to set that reference public so other objects can get it

#

β€˜public SpriteRenderer’

#

[SerializeField] without access modifier only makes it β€˜private’

tired python
#

yes, that makes sense

#

love ur pfp btw

hot wadi
#

Thanks. Just take a break after this. U might have been overwhelmed.

tired python
hybrid cobalt
#

I have been hearing things like "ECS", "DOTS", and "Burst".

Are these like different ways of programming in Unity? Is this relevant to a beginner?

naive pawn
#

Are these like different ways of programming in Unity?
they're different tools that affect the specifics of your code, but they don't fundamentally change the core way of interacting with unity afaik.
Is this relevant to a beginner?
no, learn the normal systems first - these will build on that knowledge

wintry quarry
#

ECS is a pretty fundamentally different way of interacting with and thinking about Unity imo.

rough granite
tired python
#

NullReferenceException: Object reference not set to an instance of an object mouseScript.Update () (at Assets/Scripts/mouseScript.cs:37)
so, i am currently getting this error

tired python
wintry quarry
#

Also why did you make your own class/script called spriteRender which is almost certainly causing you extra confusion?

tired python
wintry quarry
#

ok why is that second one even there

#

that just looks there to confuse me and you and everyone

tired python
#

no

rough granite
wintry quarry
# tired python no

ok sorry, taking a closer look, my guess is you have another copy of the mouseScript script in the scene

tired python
wintry quarry
#

and you didn't assign the spriteToRender variable in that one

rough granite
wintry quarry
#

oh no you're right

wintry quarry
tired python
wintry quarry
#

ok well regardless, you need to properly assign this new reference now

tired python
#

wait lemme check

wintry quarry
#

you have named things so confusingly that I think I would probably hurt myself in confusion working on this

tired python
#

oh wait, i need to attach the script on the inspector and for that i need to make it public

wintry quarry
#

what you call "Attach" is actually assigning the reference

tired python
#

i thought scritps referenced other types by themselves like when you use headers and stuff

rough granite
#

that'd only be the case for static classes

tired python
#

but when we do using something something, it does that right

rough granite
#

using somthing; is completely different heck those arent even classes

slender nymph
tired python
#

it references a header file though...am i not right

#

btw, it's working, thanks guys

slender nymph
#

c# doesn't use header files. that's just adding a using directive for a namespace so you don't need to fully qualify type names when using them in that scope

naive pawn
grand snow
#

cpp does have similar using statements but they arent always used

tired python
naive pawn
#

using in c# is like using namespace in c++

grand snow
#

be glad we dont have to deal with headers or forward declaration in c#

rough granite
grand snow
#

is java that bad? its been soo many years since I last used it

tired python
#

aight, thx for the help guys. ima go do smth else, my neck is killing me

naive pawn
rough granite
grand snow
#

i remember System.out.println and String

rough granite
# grand snow i remember System.out.println and String

not even the worst of it if you make a list, dictionary or anything of the sort you have to use the class names for the base data types so instead of int it's Integer, boolit's boolean. For inheritance it's extends, for interfaces it's implements

grand snow
slender nymph
#

C# has so many QoL features that java doesn't. java doesn't even let you define your own value types, the only value types are the primitives included with the language.
also no properties, no default parameters, no extension methods, no null coalescing, operator overloading, string interpolation

naive pawn
#

java has string interpolation now iirc

rough granite
slender nymph
naive pawn
#

as for properties, java basically just does the methods directly

#

generic constraints (extends/super, ?) are actually better in java afaict

rough granite
slender nymph
tender mirage
#

Honestly Dictionary sounds alot user friendly then, i don't know- hashmap on java.

slender nymph
naive pawn
tender mirage
#

Yes but the name makes sense. What does hashmap even stand for?

naive pawn
naive pawn
slender nymph
tender mirage
#

Oh so the hashmap name derives from a different concept that is linked to it?

naive pawn
#

map is a synonym of dictionary
map - c++, js, java
dict - c#, python

naive pawn
#

dictionary just doesn't say it

tender mirage
#

i meant like the naming convention, hashmap and the map part if you understand those

naive pawn
#

map and dict are the same thing

tender mirage
#

hashmap becomes clearer to understand?

grand snow
#

Its weird that we have List in many languages but its vector in cpp

naive pawn
#

the hash part says how it's implemented

naive pawn
#

also js calls lists arrays

#

fun times

grand snow
#

javascript is fucked anyway

naive pawn
#

they all are in different ways tbh

grand snow
#

lets just go back to having blocks of memory and pretending its an array

tender mirage
#

well that's pretty cool. I also heard they recently made something like minecraft fully open source. So minecraft modder's could have alot more freedom

naive pawn
#

none of the languages i know (which tbf isn't a lot in comparison) do generics the same way as each other
(ts, c#, java, c++, py)

naive pawn
tender mirage
#

Unless if they plan on abandoning it.

naive pawn
#

nah, corporations just hate us unfortunately

grand snow
#

No they will just stop applying obfuscation to minecraft java so the decomp will recover all naming

tender mirage
#

it's not open source.

grand snow
#

basically all managed languages have this problem, they retain soo much data you can easily decompile stuff

tender mirage
#

they're just not making it a living nightmare, after what? 15 years?

tender mirage
grand snow
#

They probably realised there is no point because the community name mappings just got updated for new content

#

so guess they thought "we might as well stop doing this"

tender mirage
#

just make it open source. Why not be user friendly? It's not like this is windows or anything, it's just a game. and it already has the biggest modding community to date.

grand snow
#

Im sure they would rather you only decomp a copy you purchased

naive pawn
tender mirage
#

corporation should be a trigger word.

glad shore
#

what would be the most simple way to add camera sway into my game?
to be more specific, whenever the player walks I want the camera to bob up and down.
I personally haven't done this before and I think it would be better to ask instead of starting blind

rancid tinsel
#

does anyone know of any repositories I could look at for examples of making a group-based combat system (one enemy attacks at a time, think like batman arkham etc.)? I've been trying to make one for our uni project for like a week straight now and I'm struggling like crazy and getting a bit disheartened

#

I'm not even sure how to describe it exactly, but an AI system where a bunch of enemies circle or move around the player and take turns attacking, rather than the standard "Walk to player -> attack"

hidden fossil
#

im having a null exception isue

#

!code

radiant voidBOT
hidden fossil
#

code

forest wolf
# hidden fossil https://paste.mod.gg/basic/viewer/zdnlrcfitoxy/0

Looks like you check if player is null or npc is null AFTER you use them so:

change this:

       bool shouldFaceRight = player.position.x > npc.position.x;

        if (player == null || npc == null)
        {
            return;
        }

to this:

if (player == null || npc == null)
{
    return;
}

bool shouldFaceRight = player.position.x > npc.position.x;
hidden fossil
#

how did that cause the error

#

wait is it cuz it runs from top to down

#

oh wait yea maybe thats why thx

gloomy bison
#

hi another question. i have a bus stop script where the gamemanager puts all the stops into a script then the person picks a random number between how long the list is and 1. is it better if i use a queue as the stops will be most likely one after the other or would a list be fine here?

#
public static List<GameObject> stops = new List<GameObject>();
public static Queue<GameObject> stopsQueue = new Queue<GameObject>();

out of these 2

#

cus atm im thinking switching to a queue although a bit of effort and time would be beneficial because i only have to dequeue instead of removing from the list which is easier

wintry quarry
gloomy bison
#

because i was thinking dequeue each stop then deactivate the stop script

#

im kinda new to the whole idea of queues so thats why im wondering

meager siren
#

Hiya, currently not at my pc and I dont want forget about this

#

But, does anyone of you know how fix a player stopping their movement when walking into a wall diagonally?

#

I think I have to use a material

#

Something Ive forgotten time and time again

wintry quarry
#

Either way you need to shuffle the order

wintry quarry
#

You're thinking of a Physics Material though

meager siren
meager siren
#

Idk if I can find it

#

On my phone

meager siren