#💻┃code-beginner

1 messages · Page 460 of 1

steel stirrup
#

^ or use tags if your class isn't a mono

dense cedar
#

wym drag in the one

polar acorn
# dense cedar wym drag in the one

Click the mouse button when hovering over one, and move the mouse without letting go of the mouse button, until your mouse is over the variable you want to assign it to, then and only then, releasing the mouse button

dense cedar
#

oh literally drag it

deft grail
polar acorn
glass totem
#

can anoyne help imhaving trouble with my save and load and nothing working none of the debugs are finding anthing i dont know if the button it on and i cant find the files for json that they are being saved to

deft grail
steep rose
#

We would need something to see for us to help you

lunar hollow
#

How do i make an infinitely moving sprite effect, where it infinitely moves in a direction? I have a sprite renderer with a Tiled Sprite.

glass totem
#

https://gdl.space/xinipihabe.cpp this is mainmenu this one gamemangerhttps://gdl.space/\ so what im trying to do is when player hit play start new game dont load save file start spawn player that it everthing lock etc. the other thing im trying to do is when the player hit save save player postion and where the camera is so i quit the game gull i can comback hit load game get the json file

main anchor
#

does anybody have a tutorial for how to create the weapon sway made in the gif below?

(Credits: Karlson by Dani)

glass totem
#

@deft grail @steep rose i posted it

slender nymph
deft grail
glass totem
#

i used that link that you guys gave me

slender nymph
#

you certainly did, you even used that exact link as your gamemanager code

steep rose
#

Dont ping me randomly dude

glass totem
#

ok

slender nymph
#

you still need to fix your link

glass totem
#

i fixed it

slender nymph
#

you most certainly did not

summer stump
#

Just put the link in. No fancy formatting

steep rose
#

I believe dani himself made a tutorial about weapon sway as well

glass totem
slender nymph
#

and have you confirmed that the code is running and that the objects being assigned are the ones you expect?

glass totem
#

yes

#

everthing is hooked up to where they should be

#

it sayin in debug player posting is saved game is save but when i hit load it loads me back to start and not to where player postion was or anthing

slender nymph
#

wait, is this happening when you like return to the main menu then go back into the game scene? or is it happening when you've closed the game and relaunched it?

glass totem
#

happening when you've closed the game and relaunched it

#

but when i open the game up agin then hit load i get loaded back to where i started

#

and not across the hallway

slender nymph
#

and you have confirmed that it loads the data and has assigned everything correctly after loading the data?

glass totem
#

yes

slender nymph
#

prove it

glass totem
#

how

slender nymph
#

show how you verified that

#

you said you confirmed it, how did you confirm that? because i don't believe that you did and i can see at least one reason why you did not in this code

glass totem
#

i was using prefs edior

slender nymph
#

how did you confirm that the data was correctly loaded and the fields/properties are being assigned correctly? that part has nothing to do with looking at the save data

glass totem
#

then i would not know then

slender nymph
#

so then the answer to "have you confirmed that the code is running and that the objects being assigned are the ones you expect" is "no, i have not confirmed that, i have only confirmed that the data is saved i have done nothing at all to ensure it was loaded and applied correctly"

#

here's a fun fact: that GameManager object will not exist until the scene it is in is loaded

#

don't ignore the errors in your console

glass totem
#

but there are none

#

that what im saying

slender nymph
#

screenshot your entire editor window with the console window open when this issue is happening

glass totem
slender nymph
#

do you have your player, vcams, and gamemanager all in the main menu? 🤔

glass totem
#

oh yeah idk if you wanted it to

#

also in game

slender nymph
#

are those the same exact objects that are in your game scene, or are they perhaps different instances of those objects? keep in mind they would need to be DDOL to be the same objects

glass totem
#

give me a sec

#

this is all my button hooked up to for the game

slender nymph
#

so you aren't setting the player's position, you're changing the position on the prefab which won't affect the instance already in the game scene. and as you can see from your own warning log and that last screenshot (which is really the only one out of all of these i needed), you don't have the vcam you were trying to assign in this main menu so naturally that cannot be assigned as well

#

you need to load the data after you've loaded the correct scene and assign to the objects that are in that scene

glass totem
#

oh so get rid of all clearshot from the code and change the positon to set and save player postin on save and load

#

instead of the other one

slender nymph
#

you already are trying to set the player's position on load, but you aren't doing it to the right object because the object you want to affect is in another scene

#

just like all those vcams i assume

glass totem
#

yes

slender nymph
#

and the reason starting a new game works is because you likely have the gamemanager with the correct references set up in your other scene and you destroy the one from the main menu when you start a new game

glass totem
#

yes

#

soo how would i fix it then pikachuface

obsidian granite
#

I'm making a game that has a system that checks if placing something in a certain position would collide with the eventual predicted path of the player. Currently, I'm instantiating an object, using Physics2D.BoxCast with the predicted path of the player, and then destroying the object. The issue with this is one of memory. I have no clue how Unity handles memory internally, but if I'm calling DestroyImmediate() on the objects, why isn't the memory immediately deallocated? I'm 90% sure it's due to the objects since the only other thing that would be using memory is just variables and structs, all of which should be WELL under a megabyte. I can't use VS memory viewer since it just... doesn't work for some reason

mint remnant
#

Garbage Collector is an independant system that handles memory cleanup. THere are ways to force it to clean up, but not sure if you have control over that in Unity

#

You can see the calls in the profiler btw, called something like GC.Alloc and possibly the clean up too, I forget

steel stirrup
#

Why are you creating and destroying objects instead of just recycling them?

mint remnant
#

THat ^^ switch to object pooling if it's a real issue

#

Basically the garbage collector IS a giant pool of objects, where the objects are sized memory chunks

obsidian granite
#

everything's happening all in one frame

#

so i think it had something to do with moving objects not being registered by physics until the next update or smth

#

idk

steel stirrup
#

It doesn't matter, and also this is going to be either fundamentally flawed design or very premature optimization

obsidian granite
steel stirrup
eternal needle
#

the part about "I'm instantiating an object, using Physics2D.BoxCast" doesnt really make sense. you dont need to create an object to use physics functions on
also ideally you shouldnt be using it for pathfinding like that

obsidian granite
mint remnant
#

something smells wrong if you're using 12gb up lol

obsidian granite
#

if it is, that means it would be in the way of the path, and i need to not spawn the object there

obsidian granite
#

i wanted to use the memory thing in vs debugging tools but it just doesn't work

#

give me c++ and allow me to manage memory myself 😔

steel stirrup
obsidian granite
#

wait actually i don't think it gets up to 12 gb anymore, that was in a worse version of the code. it gets to around ~ 5 gb and then hell breaks loose because i'm using a recursive algorithm (i'm GOING to make it iterative eventually, trust)

#

stack overflow and such

steel stirrup
#

you obviously have a memory leak somewhere

obsidian granite
steel stirrup
#

Just post the code

obsidian granite
#

it's a bit

mint remnant
#

how many objects are we talking about here?

obsidian granite
#

idk how this server works but usually people don't like long code blocks

#

all the relevant code is pretty long though

eternal falconBOT
summer stump
#

Use paste sites

steel stirrup
#

Also stop using DestroyImmediate before you accidentally kill a prefab

#

there's zero reason you should need it for this

#

or Destroy in general

obsidian granite
#

if i only ever destroy instantiated objects

steel stirrup
#

Yes, I know that's how you're using it now

#

just don't use it at all

polar acorn
obsidian granite
#

that's all the relevant code

eternal needle
#

DestroyImmediate can only destroy assets if u use the 2nd param, but u should be using Destroy anyways

obsidian granite
#

i just haven't changed it back

steel stirrup
#

needing to free the memory at all is the issue

obsidian granite
#

i thought it was coming from objects' memory not being deallocated after their destruction

steel stirrup
#

Even if it was

#

How are you possibly creating enough to use up 12gb?

#

like put that into context

#

you are using more than most computers had a few years back purely for a boxcast

eternal needle
#

use the profiler, deep profiler will quickly point you to the line causing issues

obsidian granite
#

i have NO CLUE

mint remnant
#

For starters, learn to refactor code to methods that perform a single task, see SOLID principles

obsidian granite
#

how 30 mb were being used

#

it can't be from structs and variables because... well, it just doesn't make sense

#

so i thought it must be from the objects being instantiated

obsidian granite
#

it's not getting 12 gb anymore, it gets to ~5 and then it overflows (probably just due to the amount of recursion). stack size is 1 mb, which means that my structs and variables are the things going over that 1 mb limit. therefore, the other 4.999 GB has to be stuff on the heap. i'm not doing anything with the heap besides instantiating gameobjects

#

so it has to be that, right?

summer stump
obsidian granite
#

ah okay so

#

everything happens in one frame

#

meaning that unity hard lags

#

like i can't do anything in unity until the generation is done

#

won't that affect my ability to use the profiler?

eternal needle
#

the profiler will tell you why its lagging in the first place

#

you staring at the ram in task manager wont do anything

obsidian granite
#

i'll successfully generate a level and i'll look at what's taking so much ram

mint remnant
#

for (int j = 0; j < bounceInfo.Count; j++)
{
GameObject currentPeg = Instantiate(obstacle, bounceInfo[j].pegPosition, Quaternion.identity);

THat looks scary, physics can cause lots of bounces you might not even see

obsidian granite
#

i destroy it

#

like 4 lines down

#

what that section of code does is generates pegs where it believes it is going to need to, and then checks if those pegs would interfere with the bounce it currently wants to do. if it does, then it'll change the direction of the bounce

mint remnant
#

have you ever used Extract Method in VS?

eternal needle
#

just use the profiler

obsidian granite
#

idk how to jump to a specific frame

mint remnant
#

When you see a big spike, click on it, it will pause the game and you can scroll it it

obsidian granite
#

oh wait i'm dumb as hell, profiler only captures like 300 frames

#

i need to pause quicker

#

alright cool i got the spike

#

what am i looking for?

mint remnant
#

look in the timeline section, change it to heirarchy and see what's causing it

#

or make it full screen and post a pic of it here for more tips

obsidian granite
#

oh my LORD i have to comb through the entire call stack

#

it's like 1000 calls deep

mint remnant
#

have a little recursion going on???

#

that would certainly explain 12 gb

obsidian granite
#

i have explicitly stated this

#

it is a recursive algorithm

#

it should still not be using 30 mb of memory per call

#

whether or not it's recursive or iterative, it's 30 mbs every time the code is being ran. i need to know why

mint remnant
#

well for debugging purposes, I'd put a clamp on hte depth of your recursion to maybe like 5

obsidian granite
#

oookay well now I'M stumped because the profiler is saying it's not even allocating that much memory

#

only like 120 mb, which is about what i'd expect

#

like for the 137 call deep recursion

#

wait does printing stuff use a lot of memory?

mint remnant
#

you might wanna rethink your design if your doing a 130 recursion deep call

polar acorn
#

It isn't free, but it's more CPU intensive than RAM intensive

obsidian granite
#

it will become iterative

#

i know how to mate it iterative

#

i'm trying to figure out this issue first

polar acorn
#

Still, if you're trying to profile, you should disable prints

obsidian granite
#

okay so just doing nothing besides using a midi player thing, unity's taking 2.5 gb ram. so the "5 gb" it's been taking is really more like another 2.5, but i'll see what it is without prints rq

eternal needle
#

there is also the memory profiler if you want a deeper look specifically

steel stirrup
#

The amount of ram unity is using in task manager has very little to do with your game's performance

#

I'm doing nothing and just staring at the package manager and still use ~10gb

obsidian granite
#

what??

#

10 gb doing nothing?

steel stirrup
#

Sure, unity isn't exactly lightweight

#

Rider is using another 6 lol

obsidian granite
#

like that's more than a lot of systems have to offer

steel stirrup
#

It doesn't really matter, the game itself barely uses any

steel stirrup
obsidian granite
#

i'm not talking about the build

#

i'm talking like... just being able to open the editor

#

10 gb doing nothing?

steel stirrup
#

Still doing better than firefox probably

obsidian granite
#

is rider worth it?

#

i've been meaning to buy it but i don't do anything with c# outside of unity

#

not my language of choice

steel stirrup
#

It's just an ide

#

I've never used VS, so not really sure what the differences there are

obsidian granite
#

yeah but why would you pay for it when other ides are available?

steel stirrup
#

it's cheap enough to not care

#

and ive used it forever, so why switch now

obsidian granite
#

anywho, i'm gonna look at the unity memory profiler ig

obsidian granite
#

it was the printing

#

that's what the memory leak was

#

lord have mercy

#

😭

#

i guess maybe it was all piling into a queue since it was all happening in one frame?

#

everything runs 100% fine now

errant flower
eternal needle
# obsidian granite it was the printing

printing will always be relatively slow, but now that i look at the code you have a bunch of string concatenations. string stuff always produces lots of garbage

mint remnant
#

Anyone have an algorithm that spirals out from the center of a grid instead of a double for loop that just goes left to right and top to bottom?

languid spire
# mint remnant Anyone have an algorithm that spirals out from the center of a grid instead of a...

Something like this?

    void spiralHeight(int centerY, int centerX, int maxY, int maxX, int height)
    {
        int y = centerY;
        int x = centerX;
        int da = 1;
        board.rc[y][x].height = height;
        while (y < maxY && x < maxX)
        {
            for (int i = 0; i < da; i++) fillSpiralH(--y, x);
            for (int i = 0; i < da; i++) fillSpiralH(y, ++x);
            for (int i = 0; i <= da; i++) fillSpiralH(++y, x);
            for (int i = 0; i <= da; i++) fillSpiralH(y, --x);
            da += 2;
        }
    }
    void fillSpiralH(int y, int x)
    {
        if (y < board.n && x < board.n && y >= 0 && x >= 0)
        {
            int low = 99;
            int high = -99;
            for (int dy = y - 1; dy < y + 2; dy++)
            {
                for (int dx = x - 1; dx < x + 2; dx++)
                {
                    if (dy < board.n && dx < board.n && dy >= 0 && dx >= 0)
                    {
                        if (board.rc[dy][dx].height != -99)
                        {
                            if (board.rc[dy][dx].height < low) low = board.rc[dy][dx].height;
                            if (board.rc[dy][dx].height > high) high = board.rc[dy][dx].height;
                        }
                    }
                }
            }
            if (low > high) low = high;
            int h = UnityEngine.Random.Range(low - 1, high + 1);
            board.rc[y][x].height = h;
        }
    }
#

Thats a 3D one.
This is a 2D spiral

    void spiralType(int centerY, int centerX, int maxY, int maxX, int type)
    {
        int y = centerY;
        int x = centerX;
        int da = 1;
        fillSpiral(y, x, type, centerY, centerX);
        while (y < maxY && x < maxX)
        {
            for (int i = 0; i < da; i++) fillSpiral(--y, x, type, centerY, centerX);
            for (int i = 0; i < da; i++) fillSpiral(y, ++x, type, centerY, centerX);
            for (int i = 0; i <= da; i++) fillSpiral(++y, x, type, centerY, centerX);
            for (int i = 0; i <= da; i++) fillSpiral(y, --x, type, centerY, centerX);
            da += 2;
        }
    }
    void fillSpiral(int y, int x, int val, int centerY, int centerX)
    {
        if (y < board.n && x < board.n && y >= 0 && x >= 0)
        {
            if (board.rc[y][x].type == -1)
            {
                int d = Mathf.RoundToInt(Mathf.Abs((centerX + centerY) - (y + x)));
                int r = UnityEngine.Random.Range(0, d+1);
                if (r <= d / 2)
                {
                    board.rc[y][x].type = val * 11;
                    board.rc[y][x].sizex = val;
                    board.rc[y][x].sizey = val;
                }
            }
        }
    }
mint remnant
#

Thanks, will have to try that, how sad the results from chatrgpt's version

torn blade
#

I've added a 0 Friction Material2D to the boxcollider, I set the Rigidbody2D to Interpolate.
Still my player Square (placeholder) is jittering as I walk on the Floor in the game. Why is that?
I've seperated the input and physics as one should, I dont get it.

public class PlayerMovement : MonoBehaviour
{
    public float XInput { get; private set; }
    private Rigidbody2D rb;
    private BoxCollider2D collider;

    [Header("Movement")]
    public float walkSpeed = 2.5f;

    // Transition Movement
    private float moveDistance;
    private bool isChangingLocation = false;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        collider = GetComponent<BoxCollider2D>();
        moveDistance = collider.size.x * 2;
    }

    void Update()
    {
        if (!isChangingLocation)
        {
            XInput = Input.GetAxisRaw("Horizontal");
        }
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2(XInput * walkSpeed, rb.velocity.y);
    }

    private void OnEnable()
    {
        LocationTrigger.OnLocationTriggered += HandleLocationEntered;
    }

    private void OnDisable()
    {
        LocationTrigger.OnLocationTriggered -= HandleLocationEntered;
    }

    private void HandleLocationEntered(string locationName)
    {
        if (!isChangingLocation)
        {
            StartCoroutine(AutoMoveTransition());
        }
    }

    private IEnumerator AutoMoveTransition()
    {
        isChangingLocation = true;

        Vector2 startPosition = rb.position;
        Vector2 endPosition = startPosition + new Vector2(XInput * moveDistance, 0);

        while (Vector2.Distance(rb.position, endPosition) > 0.01f)
        {
            Vector2 newPosition = Vector2.MoveTowards(rb.position, endPosition, walkSpeed * Time.fixedDeltaTime);
            rb.MovePosition(newPosition);
            yield return new WaitForFixedUpdate();
        }

        rb.MovePosition(endPosition);
        isChangingLocation = false;
    }
}
waxen adder
#

Currently brainstorming how I could create a grid out of the space occupied by a shape. This would need to account for exotic shapes like L shapes. Any ideas?

visual palm
#

should i seperate Main Menu and the game itself in different scene ?

languid spire
languid spire
waxen adder
languid spire
waxen adder
#

Would it be better to just create a custom grid?

languid spire
#

I would, It will be much faster to process it

dense pike
#

Hii

#

I need help with a money script

languid spire
eternal falconBOT
languid spire
#

Do NOT DM people without their permission @dense pike

dense pike
#

@languid spire my apologies

#

I need to create a script where the player has money and can buy guns off walls

languid spire
#

And you obviously did not bother to look on google

stable quail
#

Hi, i beginner in unity, and i don't know how to create a pickup script, my game is 2D, and i want doing :

  • the item is impacted by gravity.
  • press "E" for pickup WHENE my player touch this with a Box Collider2D.
  • the item destroy in my game for add to my inventory.
#

If someone know how to do that ? (please help me if you know)

languid spire
#

Someone else who, apparently, does not know that google exists

stable quail
dense cargo
#

It's crazy how people still assume everyone speaks the same language and has the same skills. aPES_Sip

waxen adder
#

I'd advise that if you want a more "one on one" style, you could try out ChatGPT. Just don't expect it to completely get everything right. Expect its outputs as more a rough draft than anything else

eternal needle
eternal needle
stable quail
dense cargo
stable quail
waxen adder
eternal needle
dense cargo
# waxen adder Elaborate?

AI does not understand code. It simply regurgitates what it was trained on. If you ask it to write a Harmony patch in json it will Even though that's impossile. lol You still need to know the basics before assuming AI does.

stable quail
#

my InventoryManager :

#

oh

eternal needle
stable quail
#

how to make code here ?

waxen adder
eternal needle
eternal falconBOT
stable quail
stable quail
keen parcel
#

was doing visual scripting, and then all my scripts dissapeared and this error popped up, scripts are still functional though

stable quail
#

Hi, how to do for my item don't cross my ground, he's trigger, and i want that he has a physics, how to do that ?

terse spindle
#
 void OnCollisionEnter(Collision coll){

    if(coll.collider.tag == "Obstacle"){

        Debug.Log("We Hit:", coll.collider.name);
        
    }

  }

can I make a debug log like this or do I need at least 2 Debug Logs

#

its giving an error

Argument 2: cannot convert from 'string' to 'UnityEngine.Object'CS1503
Collider Collision.collider { get; }
The Collider we hit (Read Only).

languid spire
#

look at the docs, the second parameter takes an object

sour zephyr
terse spindle
round mirage
#

why i cant destroy my GameObject (i have tried DestroyImmidiate but it dont work)
Destroy(GlassBottlePrefab);

sour zephyr
#

GlassBottlePrefab is a prefab asset, not an instance in the Unity scene hierarchy.

round mirage
#

ohhhhhhh

eager spindle
#

You want to destroy the object you instantiated, not the prefab

round mirage
#

ty

terse plume
#

is there something intrinsically wrong in tweening an Anchor in the UI? 🤔
it is working, I just want to know if this could be considered a bad practice or not

languid spire
cosmic dagger
#

make sure to keep animated UI on a separate canvas to avoid redrawing the entire canvas as it will only redraw for UI that are constantly updated . . .

terse plume
steel smelt
#

I don't get why the entire canvas would be recomputed every frame. Surely just the transformation matrix of the object being affected and its descendants?

cosmic quail
terse plume
#

actually, the fact that unity separates two canvases ain't that bad 👀

#

in unreal, changing one canvas recalculates all canvas from down there

#

because it actually makes sense, if a brother changed, maybe I changed

steel smelt
#

I'm genuinely surprised. Unity's engineers are far from bad. They'll cut corners but there has to be a reason if this is the actual behaviour

languid spire
urban wasp
#

hi,
my player can move left and right even after death of player.
how do i stop player from moving left and right?

cosmic dagger
#

disable the player input/controls . . .

urban wasp
#

how?

cosmic dagger
#

you can disable the component (used for input/controls), or set a bool (on the component) to false when dead. you only receive input when the bool is true . . .

urban wasp
#

like this?

#

but it is not working

final kestrel
#
private void OnDrawGizmosSelected()
    {
        Gizmos.color = new Color(1, 0, 0, 0.8f);
        Gizmos.DrawCube(transform.localPosition, new Vector3(.4f, .4f, .4f));
        
    }

Whats happening here? It draws the cube with offset.

cosmic dagger
cosmic dagger
final kestrel
cosmic dagger
final kestrel
#

I lifted it up so it is visible

languid spire
final kestrel
#

It is parented to my player but it manipulates the transform

#

when I try to change the local position

final kestrel
urban wasp
#

my player only get all movement from playercontroller

final kestrel
#

My player is looking to the right but the cube is facing forward.

languid spire
cosmic dagger
#

just post your !code for us the see . . .

eternal falconBOT
final kestrel
urban wasp
round mirage
#

i dont understand why i cant get the reference.

    // Start is called before the first frame update
    void Start()
    {
        cinematicTuyauEvent = GameObject.Find("CinematicTuyau").GetComponent<CinematicTuyauEvent>();
    }

    // Update is called once per frame
    void Update()
    {
        if (cinematicTuyauEvent.PlacePotion)
        {
         Destroy(gameObject);
        }
            
    }
    }```
pale ocean
#

hi all for some reason my player just starts floating whenever it collides with another surface, in this case the plane does anyone know why this is? https://hastebin.com/share/ubetalujuh.csharp

obsidian granite
#

it's a bit hard to tell

obsidian granite
#

there's nothing wrong with making a public field

#

and just assigning it in the inspector

summer stump
round mirage
obsidian granite
#

oh it's a prefab? then you can't reference an existing object via the inspector

round mirage
#

but i have put reference for a script ```if (cinematicTuyauEvent.PlacePotion)
{
Destroy(gameObject);
}

}
}```
obsidian granite
#

yeah so then assigning it in start is your best bet

round mirage
obsidian granite
#

wait why is the prefab's code running?

#

before it's been instantiated

round mirage
#

no its when its instanciate

obsidian granite
#

oh alright

obsidian granite
summer stump
#

When you instantiate the prefab, pass the reference then

obsidian granite
#

make sure that the gameobject you're referencing with .Find actually has that component

round mirage
obsidian granite
summer stump
#

var newThing = Instantiate(prefab)

newThing.variableToAssign = reference;

#

There is never a reason to use find

round mirage
#

ohhhhh ty

obsidian granite
#

.Find is pretty slow and awful so it should be a last-resort thing. i use it because i'm lazy

#

but best practice is to not use it

summer stump
#

The worst part about find is using a gameobjects name

#

There are the tag and type varieties if you really need

summer stump
#

Seriously though, never ever use find

round mirage
#

but i dont want see all my variable in the editor

summer stump
#

The tag and type varieties are still very subpar

summer stump
obsidian granite
#

is there a way to make headers have like a drop down arrow

#

so you can hide/reveal the contents under the header

summer stump
#

Or OdinSerializer or NaughtyAttributes

Or make the variables in a struct and then reference THAT , the struct will open and close

cosmic dagger
# urban wasp https://paste.ofcode.org/uZwJMXfFXmcFKVUikdPy5c

sorry, i was away. you placed the isDead check in Update for the input but you handle the movement in FixedUpdate. HandleAnimation will still use the Xinput if it wasn't 0 before the player dies. if this is true, then HandleMovement will apply velocity to the rigidbody. i'd move the isDead check to FixedUpdate instead. This will block all movement . . .

round mirage
summer stump
#

Close any graphs (like the animator) and restart unity

cosmic dagger
polar acorn
urban wasp
#

okay

#

understood, I did not mean to be rude.

cosmic dagger
#

jk . . .

urban wasp
#

I will need more help in future, hoping to be befriend 😄

umbral rock
#

so im trying to make a ledge climbing function and it works but the problem is that the player instantly transforms onto the object like u can probably see in the code, how can i make sure that the player is like slowly getting on the ledge once he collides with it?

eternal falconBOT
calm brook
rich adder
ionic zephyr
#

In a procedural generation is it better to generate all of the map at the beggining or room by room (roguelike game)

calm brook
rich adder
calm brook
#

alrighty thanks and sorry for asking this here

rich adder
#

all good 👍

normal mango
#

Trying to follow a tutorial but this won't be recognized, anyone know why?

rich adder
#

you def copied it wrong

wintry quarry
#

Try copying it correctly

#

Also make sure you capitalize things properly

polar acorn
#

And spell them correctly

#

The IDE will help with those though, once you start using the correct characters

native seal
#

what would be the best way to get a float within a given range and round to the nearest decimal. For example, if the range is 1.3-1.6, I want equal outcomes of 1.3, 1.4, 1.5, and 1.6. If the range is 1.75-2, i want equal outcomes of 1.76,1.77, etc all the way to 2

#

is this able to be done generically ?

rich adder
#

something something math.pow

wintry quarry
#

So you may wish to do things with integers. E.g. an int which represents the number of one-hundredths

native seal
#

so multiply by 10, 100, 1000, etc first?

#

how would I check how many decimal places the number has?

#

without using strings preferably

brave compass
#

The decimal type is more appropriate if you want to store fractions in base 10.

native seal
#

perhaps something like this?

#

or will i get floating point issues

rich adder
# native seal perhaps something like this?

Would this work?

 private decimal minValue = 1.3m;
 private decimal maxValue = 1.6m;
 public int decimalPlaces = 2;
...
 decimal randomValue = (decimal)Random.Range((float)minValue, (float)maxValue);
 var roundedVal = decimal.Round(randomValue, decimalPlaces);
 Debug.Log($"Rounded{randomValue} random number: {roundedVal} ");```
slender nymph
#

don't even need to use decimal for this, unity has the Snapping.Snap method that can be used for floats

rich adder
#

TIL

slender nymph
#

of course that would still be affected by floating point inaccuracy though

rich adder
#

this is kewl

 var randomValue = Random.Range(minValue, maxValue);
 var roundedVal = Snapping.Snap(randomValue, stepSize);
 Debug.Log($"{randomValue} Snapped random number: " + roundedVal);```
frigid quartz
#

Anyone know why these aren't distributing in a circle?

rich adder
# frigid quartz Anyone know why these aren't distributing in a circle?

I would use Radianscs int maxPlayers = 6; float radius = 200f; float angleIncrement = 360f / maxPlayers; for (int i = 0; i < maxPlayers; i++) { var angle = i * angleIncrement; var angleRadians = angle * Mathf.Deg2Rad; var xPos = Mathf.Cos(angleRadians) * radius; var yPos = Mathf.Sin(angleRadians) * radius; var player = Instantiate(playerPrefab, transform); player.localPosition = new Vector2(xPos, yPos); }

wintry quarry
#

Since Sin and Cos are looking for input in radians

frigid quartz
#

Ahh thank you guys, the video I was watching about sine and consines was using degrees. Thanks!

slender nymph
#

also this makes no difference since you happen to be doing a division that works with ints, but you are doing integer division with 360 / 6 so it results in an int not a float

frigid quartz
slender nymph
#

if you want the result to be a float then at least one of the numbers in the operation must be a float. otherwise it's an integer that gets implicitly cast to float. so 1 / 10 would be 0 instead of 0.1

frigid quartz
#

Any easy ideas on how I could turn this evenly distributed circle into an evenly distributed oval?

#

Oh maybe just multiply the axis' with different radiuses

rich adder
#

ya xPos = Mathf.Cos(angleRadians) * radius * xScale; .. I think

frigid quartz
ionic zephyr
#

What is the best way to program a procedular generation with a center room which stays the same? Or maybe, what is the way you like the most?

shrewd dirge
#

Hey, I want to have an object move along a path defined by a Spline from the Unity spline package, is there a script for this in Unity already?

rich adder
shrewd dirge
#

Oh, thank you!

fringe plover
#

!code

eternal falconBOT
fringe plover
ashen juniper
#

Is there any consequences to redundantly defining a variable as public when you could just use [SerializeField]?

rich adder
ashen juniper
#

So it won't increase load times or increase file size or anything like that? Basically I'm trying to decide if (as a solo coder) it's worth going back through all of my scripts to change things that don't need to be public to just [SerializeField].

rich adder
#

if you're gonna do stuff with rb

fringe plover
#

okay tysm!

ionic zephyr
#

How can I program a procedural generation with a central area from which the rest generate?

rich adder
ashen juniper
#

Cool. I won't bother changing my public variables then, just make sure I'm using [SerializeField] going forward for good practice.

rich adder
#

yeah its always better to have everything private and onyl explicitly make something public

#

for fields, use properties for public access

ashen juniper
#

Also I don't need to do "[SerializeField] private" right? It's just private by default?

rich adder
ruby python
#

Hi all,

Another brainfart moment from Spud.

if (isRotating == true)
{
    float currentMouseLateralPosition = Input.mousePosition.x;
    float mouseLateralMovement = currentMouseLateralPosition - startMouseLateralPosition;
    cameraLateralRotation.Rotate(Vector3.up, -mouseLateralMovement * orbitSpeed * Time.deltaTime);

    float currentMouseVerticalPosition = Input.mousePosition.y;
    float mouseVerticalMovement = currentMouseVerticalPosition - startMouseVerticalPosition;
    cameraVerticalRotation.Rotate(Vector3.right, -mouseVerticalMovement * orbitSpeed * Time.deltaTime);

    startMouseLateralPosition = currentMouseLateralPosition;
    startMouseVerticalPosition = currentMouseVerticalPosition;
}

I have this 'orbit camera' code that works great, but I can't for the life of me remember how to clamp the Vertical rotation of the cameraVerticalRotation Transform. 😕

ashen juniper
#

Alright, thanks for the info!

ionic zephyr
#

Does somebody know how to create a procedural dungeon map with an unchanged center room???

ruby python
#

I made something that does what you want a while ago, but tbh it's horrible coding and if I posted it here I'd more than likely get shouted at. lol.

ionic zephyr
ruby python
ionic zephyr
ruby python
#

No, it's literally just rooms and corridors

ionic zephyr
#

oh okay, thanks a lot anyway!!

manic void
#

why isn't this enabling and disabling shadows? they're just always disabled

eternal needle
ionic zephyr
ruby python
manic void
#

alright ill try that out

ruby python
# manic void alright ill try that out

Just curious, but why enable/disable them? I understand the idea behind it, but as for example the sun goes below the horizon it will stop creating shadows on your 'landscape' anyway?

manic void
#

when the moon has shadows enabled

#

then the sun doesnt make any shadows?

#

only when the shadows of the moon are disabled then they show up

#

this error happens: Cascade Shadow atlasing has failed, only one directional light can cast shadows at a time
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

proper anchor
#

i have a question

#

im new to c# and im still learning

#

im watching brackeyes course on c#

#

im on the 4th ep im just learning about loops

#

so heres ny question

#

is there any better courses i can take? after this one?

proper anchor
#

can i see ur channel?

#

and last questions

#

any tips before i go on learning c#

rich adder
rich adder
proper anchor
rich adder
#

the brackys c# are probably one of the worse ones he has

hybrid gust
#

whats the ideal way to post large amounts of code here again?

#

pastebin?

eternal falconBOT
rich adder
#

pastebin sucks

hybrid gust
rich adder
#

also heard they were sketchy at some point

hybrid gust
#

I'll take your word for it tho

rich adder
#

there is a reason its not in the Code bot

#

who does a codewebsite with half the layout being this shite

hybrid gust
#

https://hastebin.com/share/jejoduvetu.csharp
Currently running into the issue with this "lock on" mechanic where moving the mouse away from the target still keeps the transform locked to the target.

#

And admittedly hastebin is much better just cause it was like 3 button clicks and "just works"

#

gonna bookmark that, I've just been using pastebin out of habit

rich adder
hybrid gust
hybrid gust
rich adder
hybrid gust
#

gimmie a sec and I'll show u

#

Running OBS for the first time on this OS

hybrid gust
#

grumble grumble obs issues

#

there we go

slender nymph
#

use mp4 to embed video in discord, mkv requires being downloaded

hybrid gust
#

rog

#

ignore the programer art

slender nymph
#

looking at your code though:

if (lockOnPosition != null)
{
    this.transform.position = (Vector3)lockOnPosition;
}
else if (hit.collider.gameObject != gameObject)
{
    this.gameObject.transform.position = hit.point;
}

unless lockOnPosition is set to null (which only happens if something other than an ICanBeDamaged object enters the trigger) the position of that object cannot follow the mouse

hybrid gust
#

Whoops, yeah I suppose that's true

#

I've been meaning to fix that

#

guess now is the time

slender nymph
#

also you might want to consider using a physics query instead of relying on trigger messages, that way you won't end up with the issue of OnTriggerExit being called for only one of multiple objects in the trigger

hybrid gust
slender nymph
#

like an OverlapSphere, SphereCast, etc

slender nymph
#

instead of having a sphere collider that you stick to the object when it gets detected, you instead use the physics query to check the area around where your mouse is (keep the current raycast from the mouse position and just use the query at its hit position)

slender nymph
hybrid gust
#

gotta refresh my memory on how to use layermasks first to fix the first issue

slender nymph
hybrid gust
#

Also is DOTS, the same as that one system in unreal?

slender nymph
#

dots is the data oriented technology stack. i'm not familiar enough with unreal to know what "that one system" is referring to, but if you want to look at what it is then either check out #1062393052863414313 or google it

hybrid gust
#

Oh nvm, yeah no I thought it wouldve been something completely different

#

Dude unity.huh.how - how have I not found this til right now?

#

Thank you very much for the link

slender nymph
#

it's an excellent resource made by one of the mods here

uncut leaf
#

guys how would i use the on triggerstay to get the position of the object i just entered its trigger?
Image

#

like use the postion of the object for the grapplepoint

short hazel
uncut leaf
#

ahhh ok thanks

swift temple
#

How do I make the object being dragged respect the colliders of my game's borders? Right now I can simply drag the object through them. Heres the code:

languid spire
eternal falconBOT
main karma
#

guys, I want to throw a projectile like a hook using an animation, and then when it hits something, to come back from where it came from. how should I proceed?

#

I would like to also add something like curving to the trajectory or follow a different trajectory when it comes back

eternal needle
hearty trout
#

Hi

trim hedge
#

Does anyone know if there's a way to use Physics.OverlapCapsule to actually identify overlaps? I'm trying to use it but it's detecting edge touches as well, just like IsTouchingLayers would, do I have to provide something for it to detect actual overlaps?

eternal needle
trim hedge
eternal needle
trim hedge
hearty trout
#

people are telling me not to use tutorials but then if i ask something in the begginer section of any unity discord server they say to use tutorials so im confused ... so like what am i supposed to be doing to start

eternal needle
eager spindle
#

how much of unity and c# do you already know?

#

to break out of "tutorial hell" you should plan a project from start to finish and break down the features you need to do

trim hedge
eager spindle
#

when you break down what you need to do and focus on each individual task, youll learn how to do each task and inevitably watch tutorials on the way

wet monolith
#

i am trying to make jump mechanics for my platformer game but i am getting abnormal values even though i am not jumping

eternal needle
# hearty trout people are telling me not to use tutorials but then if i ask something in the be...

Who said not to use tutorials? You shouldnt be blindly copy pasting them and ideally stay away from the ones that are "build a whole game in 5 minutes!". Look up specific concepts, then build your system. Example: how to build a shop system is gonna get you an exact tutorial thatll be hard to extend upon for what you need. You'll be better off just taking the part where they look at an item to know how to "buy" it

eager spindle
#

you watch tutorials to complete a project you want to make, not watch tutorials with the sole goal of learning unity

eternal needle
trim hedge
eternal needle
raw token
#

I would assume that for digital things to touch they would have to overlap... like, otherwise, touching vs overlapping would be a matter of floating point rounding errors, right? "These things are touching but not overlapping if they're positioned exactly one floating point blind spot from each other" 🤔

Edit: or I guess just an arbitrary threshold

mint remnant
#

can you just make the collider slightly smallre?

eternal needle
#

That wouldnt matter. Now you're just overlapping with a smaller collider

mint remnant
#

how about couple a distance check along with the collision?

trim hedge
eternal needle
#

I dont know much about 2d or tilemaps but I'd assume it has a way to know what tile you're on by location or something. Otherwise it wouldnt really be a map

trim hedge
hearty trout
#

this community is so nice

wet monolith
#

i can share the code if needed

mint remnant
raw token
main karma
eternal needle
wet monolith
umbral rock
#

why doesnt this work?

raw token
#

Because that's a method, and it looks like you're trying to use it as a field or property

eternal needle
#

Read the error

umbral rock
#

yes but cant u raycast in the mouse direction?

wintry quarry
raw token
summer stump
umbral rock
summer stump
umbral rock
# umbral rock why doesnt this work?

like this? so i sent the raycast from the camera perspective and i want it to go in the direction of the mouseposition, why isnt this possible?

wintry quarry
wintry quarry
frank flare
umbral rock
wintry quarry
#

Which is the right way

raw token
# wet monolith which parameter

velocityY, such that if you are touching the ground, gravity's acceleration would not be reflected in the animator.

Alternately, depending on how gravity is applied, you may be able to set that parameter prior to the velocity reflecting gravity

umbral rock
#

so camera.screentopointtoray is not a vector 3? thats why it cannot be in the direction argument?

wintry quarry
#

First of all of like it says, it's a ray

#

Read the documentation to see what the function returns

wintry quarry
#

Or just look at it in your IDE

#

It returns a Ray

umbral rock
#

Vector3 direction

wintry quarry
#

Second of all, you failed to properly call it as a function

#

Which requires () and providing the parameters

wintry quarry
craggy otter
#

anyone has a reference to the mario bros movement? im making the 1-1 level of smb with learning pruposes but my movement is not to mario, any improvements or resources out there?

umbral rock
#

in the documentation stands a vector3?

short hazel
#

You can see which overload it selected by putting the mouse over Raycast in your code

umbral rock
#

Camera.screentopointtoray is not a vector 3 so i cant put it in those arguments?

steep rose
#

Look it up on docs

short hazel
#

C# selects that one:

#

Which does take a Ray as the first parameter

main karma
short hazel
#

Raycast from the mouse position into the scene, apparently

#

Which works, it's a matter of reading the documentation

main karma
#

there are some great tutorials for that out there actually

summer stump
wintry quarry
umbral rock
#

ahh ok got it, thanks!

queen adder
#

!code

eternal falconBOT
queen adder
#

is this the proper way to Invoke a method from another script it isnt worming so obviously not but how would I?

 script.fadeIn();
 Invoke("script.fadeOut", 1);
cosmic dagger
slender nymph
cosmic dagger
#

Invoke will only call methods on the GameObject itself . . .

#

but yeah, do what box mentioned . . .

queen adder
wintry quarry
#

Coroutine is better too, yea

queen adder
wintry quarry
#

But regardless, let it handle its own invoking

queen adder
queen adder
slender nymph
#

it does not

queen adder
#

sweet thanks everyone

terse spindle
#

hello

#
rb.AddForce(0,0,-1000 * Time.deltaTime);
#

how to apply force for a certain amount of time

deft grail
terse spindle
#

like in the mobile games you hit an obstacle you go back a bit then stop

slender nymph
#

for that a simple impulse force would be all you need rather than applying force over time

#

also don't multiply your forces by deltaTime, ForceMode.Force already takes that into consideration and you must be applying constant forces in FixedUpdate rather than Update

cosmic dagger
terse spindle
#

originally this was for keeping the player running

#

basic game tutorial

#

I just thought it'll work like this also

deft grail
terse spindle
#
void OnCollisionEnter(Collision coll){

    if(coll.collider.tag == "Obstacle"){

        Debug.Log("We Hit" + coll.collider.name);
        plrmovement.enabled = false;
        
        rb.AddForce(0,0,-1000 * Time.deltaTime);
        
    }

  }
terse spindle
#

I think we're in beginner

deft grail
#

impulse is beginner

polar acorn
#

That's a message link

#

click it

terse spindle
#

oh

#

sorry man

#

impulse force let me try

#
rb.AddForce(0,0,0, ForceMode.Impulse);
#

like this?

deft grail
slender nymph
#

well that won't actually do anything on account of it adding 0 force on all axes

terse spindle
#

okay I'll edit that

#

is there a way I can make it faster

deft grail
#

change gravity and stuff

#

or wdym by "faster"

polar acorn
slender nymph
#

and make sure you aren't doing something silly like completely overriding the velocity of the RB somewhere

terse spindle
#

I did something like this

 IEnumerator MovementAfterForce(){
        rb.AddForce(0,0,-10, ForceMode.Impulse);
        yield return new WaitForSeconds(2);
        plrmovement.enabled = true;

  }


  void OnCollisionEnter(Collision coll){

    if(coll.collider.tag == "Obstacle"){

        Debug.Log("We Hit" + coll.collider.name);
        plrmovement.enabled = false;
        StartCoroutine(MovementAfterForce());
        
    }

  }
#

it works alrighhtt

deft grail
terse spindle
#

slight problem

ivory bobcat
#

What would happen if you hit twice UnityChanHuh

terse spindle
#

oh it just repeats itself

#

if I hit twice

ivory bobcat
#

Except the first coroutine might've reset the player movement before finishing the yield for the second

terse spindle
#

but my character's speed slowly increasing is there a way to make it straight

deft grail
terse spindle
#

like I hit the obstacle high speed and my -10 force does nothing and I hit it again when plrmovement is enabled

ivory bobcat
slender nymph
#

reset the player's velocity to 0 before adding force, otherwise the force needs to overcome its existing velocity

deft grail
terse spindle
#

yeah I know

#

how does "completely overriding the velocity of the RB" work

#

how do I even do that

slender nymph
#

well if you assign to its velocity property anywhere that overrides what the velocity currently is

deft grail
steep rose
#

Rb.velocity = vector3.zero I believe resets it

#

Correct me if I'm wrong

terse spindle
#
rb.AddForce(0,0,forwardForce * Time.deltaTime,ForceMode.Impulse);
#

forward force is 10

terse spindle
#

okay

deft grail
#

you were told this earlier

terse spindle
#

chill

#

uh now my character is flying

#

why do I need to remove it what does it do

steep rose
#

Remove what?

terse spindle
#

Time.deltaTime

#

oh bro

#

its in void loop

#

its looping going forward

summer stump
#

Do you mean Update?

terse spindle
#

yeah

#

sorry

cosmic dagger
#

void loop?

summer stump
#

Void is just a return type btw. Don't use that in the name

raw token
#

Good game name 🤔

steep rose
#

Always apply forces in fixedupdate() btw

terse spindle
#

okay btw

#

why tho

summer stump
terse spindle
#

it works great in normal update

summer stump
summer stump
steep rose
terse spindle
#

should I make another void FixedUpdate for it

#

just 1 line of code

summer stump
deft grail
terse spindle
#

letme try

summer stump
#

Oh, if you have one already, then just use that
You absolutely cannot have multiple

terse spindle
#

I can do that

summer stump
terse spindle
#

thats what you said

summer stump
#

Ok, I thought they were saying you had more than one FixedUpdate

#

Update and FixedUpdate are obviously perfectly fine

terse spindle
#

so I dont need two updates

raw token
# terse spindle why do I need to remove it what does it do

Time.deltaTime is the time since the last frame (or physics update, depending on where it's used) in seconds. So it's useful to figure out a distance from a velocity, for example - you multiply the velocity by the amount of time which has passed.

But it doesn't make sense to multiply an instantaneous force by a time. You want all of the force now - no reason to scale it down

steep rose
#

Remove deltatime, its arbitrary when in fixedupdate

summer stump
#

Never ever use deltaTime in AddForce

deft grail
summer stump
#

Or with velocity

terse spindle
summer stump
#

Multiplying it by deltaTime (a tiny decimal) will of course reduce the force a lot. So when you remove it, you have to decrease the force

terse spindle
#

I saw something that update is working every frame so more fps I got , more speed I got

#

delta time is making it

summer stump
#

AddForce ALREADY has deltaTime in its force internally

terse spindle
#

eh how can I say

summer stump
#

Never ever ever ever use deltaTime in AddForce

terse spindle
summer stump
slender nymph
# terse spindle

if this is just to move it continuously, then do not use ForceMode.Impulse for this, ForceMode.Force would be more appropriate. Impulse is for an impulse of force, or one-off forces that should apply all of the force all at once

summer stump
#

Also, why are you using Impulse -ah too slow

terse spindle
#

I dont know bro just trying different things

deft grail
#

pretty sure it running every frame is not what he wants, and impulse is what he wants
but who knows 🤷‍♂️

terse spindle
#

so I dont use deltaTime in fixedupdate

raw token
#

Impulse in the OnCollision message made sense 👍

terse spindle
#

let me try

slender nymph
raw token
#

ah

terse spindle
#

one for continusly moving forward

#

one for

#

backing off

summer stump
terse spindle
#

so I use for impulse for back off

deft grail
#

thought you just added a variable since it had the same value and you pointed that out

terse spindle
#

and dont use impulse for continuesly

summer stump
#

You can certainly use deltaTime in FixedUpdate (it will convert to fixedDeltaTime though)

terse spindle
#
 void FixedUpdate(){
        rb.AddForce(0,0,forwardForce,ForceMode.Force);
    }
#

so Like that huh??
?

slender nymph
# terse spindle backing off

for your impulse to knock it back, you will also want to reset the velocity to 0 immediately before the knockback

terse spindle
#

am i right

slender nymph
#

right, since your knockback force is similar to the amount of forward force the object will already be affected by if you don't reset the velocity before the knockback at best it might be knocked back only a little bit

terse spindle
#

so how do I set velocity 0

#

rb.velocity?

#

the guy said

#

rb.velocity = vector3.zero

deft grail
terse spindle
#

I try and its good

#

but Im not sure if the player is always in same speed

#

how can I know that

#

I feel like its getting more speedy every second without hitting an obstacle

deft grail
terse spindle
#
Debug.Log(rb.velocity);

??

slender nymph
#

if the rigidbody does not have drag or any other forces acting on it, then yes you are constantly accelerating

terse spindle
#

angular drag of 0.05

raw token
#

That will work against angular velocity, but not linear velocity

terse spindle
#

its getting speedier every second

raw token
#

Add some Drag

terse spindle
terse spindle
raw token
#

The running force will eventually reach an equilibrium with the drag force, effectively resulting in a top speed

terse spindle
#

it worked but I didnt understand how it did

tardy plaza
#

hello i have a question regarding two scripts that i've written, one script takes a mouse input and info from a raycast and the other script takes this info and decides wether or not to deactivate itself, the code works fine, but when i duplicated the game object that would destroy itself and tested the code, both the og and the duplicated object were destroyed when interacted with. i basically need them to destroy when interacted with separately rather than both with one interaction. Could anybody help? id rather dm the code so its a bit quieter

raw token
# terse spindle it worked but I didnt understand how it did

You're accelerating your character by applying a force. The drag force is applied to your character in the direction opposite of their current velocity.

Drag force is calculated as a function of the magnitude of the character's velocity and the Drag value you set as a multiplier. So as the character moves faster, a greater drag force is applied against them. When the character is moving fast enough, the drag force will become large enough that it's equal to the force you are applying to move it - the two forces cancel each other out, so the character just maintains it's current velocity instead of accelerating.

When your Drag was set to 0, it totally disabled the drag force, so there was no resistance to the acceleration.

raw token
tardy plaza
#

i also dont want people judging my code i have NO clue if it is effecient at all, im happy to post it here directly

eternal falconBOT
deft grail
#

your not the only one with bad code, pretty much everyone has something bad

#

so dont worry

tardy plaza
#

i have it ready to post

mint remnant
tardy plaza
#

'''cs

#

oops

#

mb

deft grail
tardy plaza
#
// using UnityEngine;

public class SprayToggle : MonoBehaviour
{
    public bool canSpray = false;
    public bool spraying = false;

    [SerializeField] LayerMask glass;

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

        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hitinfo, 5f, glass))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hitinfo.distance, Color.red);
            canSpray = true;
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 5f, Color.green);
            canSpray = false;
        }


        if ((Input.GetKeyDown(KeyCode.Mouse0)) && (canSpray == true))
        {
            Debug.Log("spraying");
            spraying = true;
        }

        else
        {
            spraying = false;
        }
    }

#

this is the first script

young coral
#

hello, whats the blender donut equivalent of unity? i havent installed it yet but i really want to get started and i dont even know how to code

tardy plaza
#
// using UnityEngine;

public class smudge : MonoBehaviour
{
    public SprayToggle wipe;

    private void Update()
    {
        bool spraying = wipe.spraying;

        if(spraying == true)
        {
            Destroy(this.gameObject);
        }
        else
        {
            gameObject.SetActive(true);
        }
    }
}
#

second

deft grail
mint remnant
#

why using UnityEngine commeted out?

raw token
eternal falconBOT
#

:teacher: Unity Learn ↗

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

tardy plaza
young coral
tardy plaza
#

personal preference

#

the issue is that when i duplicate the gameobject with the second script, when the first script interacts with the gameobject via the raycast both objects get destroyed

#

if that makes sense, i just need a way of indavidualising each gameobject somewhere in the script i think, but i cant think of anything

mint remnant
#

as for judging your code it actually doesn't look that bad, small concise methods, using some debug drawrays to help

raw token
young coral
raw token
# young coral thanks, also i found a 10h long video on unity, should i watch it in parts or sh...

It's kind of hard for random YouTube videos to target their entire audience's skill level as it varies so widely. So some sort of foundational knowledge from more structured content is definitely useful before wandering out into the wilderness. But an introductory 10 hour video may offer that sort of structure 🤷.

I kind of followed the Learn content and challenged myself to integrate stuff I was learning about in my projects through other avenues along the way, which worked well for me, but I can't say if it would work well for everyone

raw token
# tardy plaza the issue is that when i duplicate the gameobject with the second script, when t...

That makes sense - all of the smudges will check every frame if wipe.spraying, and blow themselves up if so.

A more common solution to interacting with specific instances like that is to have whatever's performing the raycast try and get the "second script" component from whatever it hit, and if found, call a method on it. That way whatever functionality needs to happen is only executing on the relevant instance (and you don't have a bunch of objects constantly checking if they should do something 😁)

young coral
cosmic dagger
tardy plaza
raw token
# tardy plaza so make the first script deactivate the necessary gameobject rather than the sec...

You could, totally!

But often times and definitely for more complex scenarios, it doesn't make sense to have all that logic relevant to those objects contained in the class which is raycasting. So instead the raycaster just calls a method on what it hit. This way, the class on the object which was hit is still responsible for all of it's own logic and behaviors - the raycaster just kicks things off

#

Although in this case, a wiper destroying smudges does sound totally reasonable 🤔

tardy plaza
#

the premise of the game is a cleaning game if you hadnt guessed already

tardy plaza
main karma
#

really good course, honestly I dropped it like 2 thirds in after I learned what I needed to start my own game, afterwards I just try to make something with the info I know, end up messing up, so I either look up a tutorial, documentation or ask here if nothing else works. I recommend digesting the information and then applying it by yourself to your own ideas

tardy plaza
#

i wrote another script that works fine for a vaccum, it works off of collision detection. I was hoping there would be a way to physically check if a raycast was touching a collider, by checking the tag, layer or name of what was outputting the ray and perform a method off of that is there ANY way to actually do this

deft grail
tardy plaza
#

but could the object being hit by the raycast check where the raycast was coming from?

deft grail
tardy plaza
#

ah okay got it

#

just wanted to confirm 👍🏾

eternal needle
tardy plaza
#

yeah im just grasping at straws and trying to find an easy work around its not really working 😦

eternal needle
tardy plaza
eternal needle
tardy plaza
#

there are two scripts posted

#

im just fiddling about with the logic as you said and trying different things, im sure it will click eventually 🙂

eternal needle
tardy plaza
#

yeah thats the issue

eternal needle
#

The spraying script should call a public method on the smudge script to let it know to destroy itself. At least that's what I assume you want

#

The smudge doesnt need to use update at all here

uncut leaf
#

!code

eternal falconBOT
uncut leaf
#
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class TimerController : MonoBehaviour
{
    public static TimerController instance;

    public TMP_Text timeCounter;
    public TMP_Text highScore;

    private TimeSpan timePlaying;
    private bool timerGoing;

    private float elapsedTime;

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        timeCounter.text = "00:00.00";
        timerGoing = false;
        BeginTimer();
    }

    public void BeginTimer()
    {
        timerGoing = true;
        elapsedTime = 0f;

        StartCoroutine(UpdateTimer());
    }

    public void EndTimer()
    {
        timerGoing = false;
    }

    private IEnumerator UpdateTimer()
    {
        while (timerGoing)
        {
            elapsedTime += Time.deltaTime;
            timePlaying = TimeSpan.FromSeconds(elapsedTime);
            string timePlayingStr = timePlaying.ToString("mm':'ss'.'ff");
            timeCounter.text = timePlayingStr;

            yield return null;
        }
    }
}

#

how would i turn this to add a highscore part

summer stump
#

I would make that completely separate

uncut leaf
#

i want to save ur time when u get a lower time then ur previous highscore

tardy plaza
silent valley
#

Just asking out of curiousity. May someone explain how this line of code works? I've never used a ? in a line of code before

summer stump
tardy plaza
uncut leaf
summer stump
#

Then just a single if checking if current score is better than currentHighScore

summer stump
#

Get some save and load functionality, hopefully using json or something (many guides online)
Bada boom, done

uncut leaf
#

ok so i would save ur scores into a json file on ur computer?

#

and i should probably encrypt it so ppl dont change their scores right?

summer stump
summer stump
#

Any and ALL encryptions can (and will) be broken
Especially ones for games because people love doing that

eternal needle
uncut leaf
#

thanks for the help

tardy plaza
#

i guess so but i will cross that bridge, thank you anyway massive help 🙏🏾 🔥

deft grail
white rune
#

Aye fellas, im tryina get a wave system for this lil game workin. The OnDestruct is meant to keep track of how many enemies are currently alive, so im trying to get it to run within the enemy's script so it can trigger upon the death of the enemies, but it keeps throwin up the error in the first image. Anyone know what's up? (The last two are from the enemy's script)

deft grail
#

and best not use a screenshot at all !code

eternal falconBOT
white rune
#

gotcha, gimme a tick to reformat it

#

Its got a prob with callin the foreign function

deft grail
#

the object with EnemyClose on it

white rune
#

Oh, no

#

Im assumin I gotta set it so it gets the object with the actual script on it

deft grail
#

thats why it errors

white rune
#

I sees I sees

deft grail
#

or just reference the script itself

waxen adder
#

I have a grid built and I'm trying to process mouse clicks on the grid. I have it more or less working with raycast stuff, but I want to make sure I only click the top of these tiles though. Any ideas?

mint remnant
#

check that the normal from the raycast hit is in the .up diretion

waxen adder
#

What about in the scenario of "ramp" tiles?

teal viper
cosmic dagger
mint remnant
#

use a layermask to exclude other objects

white rune
waxen adder
#

Er oh you meant hit

#

Just realized that while I was typing XD

cosmic dagger
#

also, in OnDeath you set currentlyAlive = false then check if it's false in the next line. it will always be false because you just assigned it, so they if check is unnecessary. the same applies to if (isDead == true). you just assigned it to true right above, so it will always be true . . .

waxen adder
teal viper
waxen adder
#

No, but from testing it seems like it would have at least some kind of +y component (if at least somewhat facing up), unless I tested it wrong

lean anvil
#

kind of confused right now with this error

rich adder
lean anvil
#

I dont think I did and im pretty clueless on where to do it

rich adder
lean anvil
#

the gameinput script was already in the player gameobject

rich adder
#

oh I was looking at wrong script sorry

#

you initialized the Input script as local variable, just remove the first PlayerInputActions from the new() so its not a new local copy

#

mybad

native thorn
#

Where do I go for information about serialisation and save systems for persistent worlds

#

Is this an incredibly complex thing that's typically handled by professional software Devs or

rich adder
#

your best bet is using json or something easy like that

native thorn
#

I guess I'm totally unaware of how it interacts with the engine and what's actually happening

rich adder
native thorn
#

Alright, that's good to hear

rich adder
# native thorn Alright, that's good to hear
void SomeMethod()
{
    SomeData someData = new SomeData(69, true);
    var jsonString = JsonUtility.ToJson(someData);
    File.WriteAllText(Path.Combine(Application.persistentDataPath, "saveFile.dat"), jsonString);
}
public struct SomeData
{
    public int SomeNumber;
    public bool SomeBool;
    public SomeData(int someNumber, bool someBool)
    {
        SomeNumber = someNumber;
        SomeBool = someBool;
    }
}```
Very simple example
native thorn
#

Oh very easy, alright cheers

obsidian granite
#

just finished rewriting my recursive algorithm to be iterative, i feel like i've never been more with the call stack than i was during this project

willow scroll
waxen adder
#

How do I use find on a list of structs? Getting confused by online resources

#

More specifically, I want to find a struct, based on only one of its elements being matched

raw token
# waxen adder How do I use find on a list of structs? Getting confused by online resources

I had never considered it before... If no match is found, Find() would still return a struct with every member set to the default value for its' type...

From what I'm reading, it sort of sounds like you'd need to test your conditions against Find()'s return value to see if it really found a match or not, which seems cumbersome.

One nice sounding alternative is to use FindIndex() instead (since it has a more definitive return value) and then just get the matching struct by that index, if it exists

charred spoke
#

Or you know just loop over the list and test the condition yourself.

#

If match break; simple as

waxen adder
waxen adder
#

In my struct, I have an object, so it would be null as default iirc

willow scroll
#

I have always used First (FirstOrDefault) & Select

waxen adder
#

I'm the opposite lol

#

Though that's because I've been deep in unrealscript, where doing this whole find process is surprisingly easier and gives you the index in the list instead

raw token
# waxen adder What do you think of something like this? ``` GridNode result = gridNodes.Find(n...

Should work... kind of a bummer to allocate another struct each time though. You might just store the predicate somewhere and reuse it on the result (if this is happening really frequently, anyway - one extra allocation won't matter much otherwise).

But I'm pretty sure Find() is more expensive than a simple loop, what with all the call stack cycling and such.

I sort of feel like maintaining a separate index on the gridPos member might be worthwhile, if you do find this to be a performance bottleneck at some point.

waxen adder
#

Hmmm. Sounds like I might run a loop after all lol.

I guess this is all happening at start, and shouldn't really be happening afterwards, so whatever performance hit this gets only really happens once

charred spoke
waxen adder
#

I do, but I imagine that's a misconception at this point

charred spoke
#

If performance is an issue you could always implement your search as a parallel job

#

It is O(n) right now so performance really depends on the size and given how stupid fast cpu’s are I doubt you will see an issue

waxen adder
#

I agree, even more so since this is most likely only going to be happening in a "loading" phase

#

Could turn this list of structs into a dictionary too potentially

charred spoke
#

How would that help ?

keen dew
#

All this is premature micro-optimizing. Surely you have more pressing issues to spend your time with

waxen adder
charred spoke
#

The lookup of the list is also constant

#

Like list[5] will not be slower than accessing a dictionary with a key

#

Actually the index 5 here is the key

#

In a way ofc

waxen adder
#

Right, but in my situation, I wouldn't know the index. I would know the key though

charred spoke
#

What would be the key ?

waxen adder
charred spoke
#

That would still loop over the key values until it finds one

#

Not faster than looping the list

waxen adder
#

;.;

eternal needle
#

I too dont even see how a dictionary would work here. You have vectors only, what value are you trying to associate it with

#

The answer is simple: profile it and see that it runs literally instantly anyways with a list.

#

If the list doesnt have 10k elements in it, dont worry about the speed

charred spoke
#

Even if does have 10k elements 🤣

#

I would worry for 100k to begin with

#

Like I said cpu’s are stupid fast

eternal needle
#

True

waxen adder
#

I'm curious, where would it even get bad?

eternal needle
#

When you start to notice lag spikes

charred spoke
waxen adder
#

Time to slam 5 trillion elements into the list 😛

eternal needle
#

You could literally add a for loop going through 0 to 1 million every frame and still be above 100 fps on most computers

charred spoke
waxen adder
#

UHHHH. 1 billion is ummm. Taking some time. Might have to do with having to spawn 1 billion cubes tho

jolly temple
#

Hello, I wanted to create a code so my animation can work, can anyone help me?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 10f;
    public float gravity = -9.81f;
    public float jumpHeight = 5f;

    public Transform groundCheck;
    public float groundDistance = 5f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded = true;

    void Update()
    {
        // Movements
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        Debug.Log(isGrounded);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");

        Vector3 move = transform.forward * x * speed;

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move((velocity + move) * Time.deltaTime);
    }
}
#

here's the code

#

I already added the animation to the Animator tab, and I just need to code so the Animaton will work

verbal dome
jolly temple
languid spire
# jolly temple I mean, I want to add a code so that when I press the D key my character will pl...
Unity Learn

In this course, you'll explore the fundamentals of Unity’s 3D animation systems. You will: Review the core concepts for the animation systems in Unity Connect those core concepts to the functionality of the Unity Editor Apply your learning through creating and modifying simple animations Review key principles of scripting for animation
By the e...

verbal dome
#

You would do that by setting an animator parameter (bool/float/int) from your script

#

And having a transition that uses that parameter set up in the animator

#

Definitely check out that intro^

ruby flower
#

how do you code smth like this in the inspector tab so you can insert your own things

steel stirrup
ruby flower
#

is it possible with visual scripting too?

steel stirrup
#

to be able to display an entire class (ie in the case of wanting to show something like List<Weapon>) mark the class as [System.Serializable}

steel stirrup
ruby flower
#

thx