#💻┃code-beginner

1 messages · Page 185 of 1

buoyant knot
#

and know that when you execute Physics2D.Simulate, the game will:

  1. Solve physics,
  2. move stuff
  3. Execute collision/trigger callbacks
#

all of this happens in that line. you cannot wedge any code in between, and know that any code you write in the lines after Simulate() is AFTER all OnCollision… basically like LateFixedUpdate (if it were a thing)

silver flicker
#

got it

#

ill look into that a little bit more in that case

buoyant knot
#

just giving you info because the documentation does not have the details

#

it might as well say “run the physics simulation lol”

silver flicker
#

Yeah I can see that on the website lol

#

i appreciate it

ashen wind
#

is there a way to check collision without using ontriggerenter2d and ontriggerexit2d?

#

like check immediate collision?

#

I'm trying to do a thing where I place a building only if it's not intersecting with another 2d collider

#

and have it be greyed out if it is intersecting

#

but for that I need a bool that's only true when no colliders are intersecting

#

and the enter and exit functions are not behaving as expected

#

nvm, figured it out. It's OverlapCollider()

craggy oxide
#

Can someone explain this snippet to me? (Taken from the Unity documentation site)
I get that it creates a raycast 10 units forward from the GameObject

But how is it an If statement
And how does it detect that there's something in front of the object

#

this is the full thing

polar acorn
craggy oxide
#

So the if statement actually creates the raycast and listens for it returning true simulataneously?

polar acorn
swift crag
#

I wouldn't say anything is "simultaneous" here

craggy oxide
#

casts the ray

rare basin
#

it's a bool type method

swift crag
#

if (whatever) evaluates whatever

polar acorn
#

It is just checking if anything in that line

#

it's math

#

no objects are created or listened for

swift crag
#

in this case, it evaluates Physics.Raycast(transform.position, fwd, 10)

#

If that expression evaluates to true, then it executes the following statement

polar acorn
#

it checks if the line with those properties intersects a collider, and returns true if it does

craggy oxide
swift crag
#

It never "returns" anything.

polar acorn
craggy oxide
swift crag
#

In this case, since there's no else or else if, it just skips its statement and execution continues.

polar acorn
craggy oxide
#

probably not

polar acorn
craggy oxide
#

yeah i've just never used it in such an odd context

#

well, odd to me

#

i'm a beginner

#

usually my ifs actually listen for say... a trigger or two values syncing up or something

polar acorn
craggy oxide
#

ive never encountered an if statement that listens out for something like that

swift crag
#

you are over-thinking how if works

#

It doesn't "listen"

summer stump
#

if (MethodThatReturnsABool())
Think of it like that

polar acorn
swift crag
#

It evaluates an expression.

craggy oxide
polar acorn
#

it literally just checks a true or false

swift crag
#

If the expression is true, it executes its statement.

craggy oxide
polar acorn
#

like always

swift crag
#

That's all it does, ever.

polar acorn
craggy oxide
#

alright alright i get it

swift crag
#
if (true)
if (1 == 1)
if (3 < 5)
if (MethodThatReturnsTrue())
if (6 != 4)
craggy oxide
#

I GET IT

polar acorn
#

if (someBoolean) also evaluates an expression

swift crag
#

all of these will have the same outcome

craggy oxide
#

All I need to know is, does the if statement evaluate the raycast returning true/false, and then executes the following statement if it returns true

#

Yeah?

swift crag
#

As always.

polar acorn
craggy oxide
#

Alright, thank you

swift crag
#

There is nothing special here, and there's never something special here.

#

We are confused about why you're asking the question at all.

#

It suggests you misunderstand something.

summer stump
buoyant knot
#

raycast is overloaded

craggy oxide
polar acorn
buoyant knot
#

can return a bool or a raycasthit2D

buoyant knot
#

oh, idk about 3D

polar acorn
#

you can't overload a return type

craggy oxide
summer stump
craggy oxide
#

i think i get it

craggy oxide
buoyant knot
#

2D raycast can return an int or RaycastHit2D

craggy oxide
#

i'm just bad at phrasing this

swift crag
polar acorn
# craggy oxide alright....

That function returns true if the line you define intersects a collider.
It returns false if the line you define does not intersect a collider.

That's it

craggy oxide
#

okay anyway i got all i needed so thank you

summer stump
buoyant knot
#

why did they do it this way? idfk, but they did

polar acorn
#

They did things slightly different

#

My guess? The 2D people didn't know out parameters existed

buoyant knot
#

2D physics methods are strange. they populate arrays/lists that you feed in so they can do everything non-alloc. But they don’t pass them in as ref

polar acorn
swift crag
#

you don't need to pass them as ref

fiery fjord
#

I am making a multiplayer game using Relay. Everything is working correctly and connecting fine, but I am having an issue with NetworkVariables.

For some reason, after my client joins the server, it does not retrieve the values such as the "LobbyCode" NetworkVariable nor does it retrieve the "LobbyNames" NetworkList.

The first image is where the problem occurs and both NetworkVariables are default when retrieved while the second image (Creating a lobby), the variables are set correctly. It's almost as if the client is setting the variables as default while the client should not have any write perms.

Any help would be greatly appreciated! (P.S. unsure if there is a channel specifically for multiplayer questions, I'm sorry if I am in the wrong spot)

swift crag
#

that wouldn't really accomplish anything unless you wanted to completely overwrite the variable the user provides

buoyant knot
#

at least in the context of lists and arrays

polar acorn
#

if that type was a value type. Arrays are reference types

buoyant knot
#

right now, you’re just kind of expected to know that the input array is actually getting modified

swift crag
#
public void MessWithList(ref List<int> theList) {
  theList = new();
}
#

this assigns a new list into whatever variable was passed as an argument

#

vitally, this is nothing like just modifying the contents of the list you were given

#
public void MessWithList(List<int> theList) {
  theList.Add(123);
}
buoyant knot
#

correct, but how else do you indicate that your method is going to actively modify the contents of the collection?

swift crag
#

by documenting it

#

ref should not be used for documentation purposes

#

the parameter name should make it obvious, and the method's documentation should also describe what it's going to do

swift crag
#

ref does not mean "I might modify your reference type"

buoyant knot
#

the non alloc methods are effectively taking in your variable and messing with it, as though they have a ref to it anyway

swift crag
#

no, they do not

#

they mess with the thing you have a reference to

#

they don't touch your variable at all

buoyant knot
#

true. I just find it strange to make methods that try to modify the input

swift crag
#

every instance method is a method that modifies its input (:

buoyant knot
#

input arguments

swift crag
#

what is this but an implicit zeroth argument?

buoyant knot
#

i expect an instance’s methods to be able to modify the instance

#

that is sus

polar acorn
swift crag
#

C# gets mad if you call a static method from an instance..

#

C# has no equivalent to c++'s const qualifier on methods

#

which promise that the method has no effect on the instance

deep quarry
#

This is my script for accelerating my rocket:

    void MyInput()
    {
        if(Input.GetKey(KeyCode.LeftShift))
        {
            accelerating = true;
        }
        else {
            accelerating = false;
        }

        if (accelerating)
        {
            if (moveSpeed !< maxSpeed) 
            {
                Debug.Log("Accelerating!!");
                moveSpeed *= 1.001f;
            }
        }
        else {
            moveSpeed = moveSpeed / 1.02f;
        }
    }

Later, I add a force by:

        if(accelerating) 
        {
            rb.AddForce(Vector3.up * moveSpeed * Time.deltaTime, ForceMode.Force);
        }

However, when I press LeftShift the moveSpeed variable doesn't increase. When I remove the

        else {
            moveSpeed = moveSpeed / 1.02f;
        }

part it works. Any idea why?

swift crag
#

!< does not do what you think it does

#

you've actually written moveSpeed! < maxSpeed

#

although I guess that's technically fine here

cosmic dagger
#

!< 🤔 is different than you think . . .

swift crag
#

you probably just wanted moveSpeed < maxSpeed

short hazel
swift crag
#

Ah, there it is!

cosmic dagger
#

If you want "not less than," that is called "greater than" . . .

deep quarry
swift crag
#

That shouldn't change anything, though

#

! is the null-forgiving operator, which isn't going to do anything here

deep quarry
#

Well it works now :3

swift crag
#

Perhaps you had that else { moveSpeed = moveSpeed / 1.02f } in the wrong place before.

twin bison
#

Hi guys. Beginner question: Why is this code not showing up in the inspector of the object:

public float BulletSpeed { get; set; }
#

if i leave { get; set; } away it will show up

#
[SerializeField]
public float BulletSpeed { get; set; }

Wont work either unfort

languid spire
#

because properties are not, by default, serializable

swift crag
#

public float BulletSpeed; declares a field.

languid spire
twin bison
#

Ok that works. Whats the difference between these two:
A:

[field: SerializeField]
    public float BulletSpeed { get; set; }

B:

[SerializeField]
    private float BulletSpeed;
swift crag
#

public float BulletSpeed { get; set; } declares a property with auto-implemented properties

#

properties "look and feel" like fields, but a method is called when you read or write them

twin bison
languid spire
swift crag
twin bison
swift crag
#

hence needing to specifically target the backing field with [field: ...]

#

otherwise your attribute targets the property

twin bison
#

but now that it works and its my kinda first steps with OOP im kinda proud of this:

abstract class Weapon : MonoBehaviour
{

    void Start()
    {
        Debug.Log("Start");
        Shoot();
    }

    [SerializeField]
    public float Damage;
    [field: SerializeField]
    private float BulletSpeed { get; set; }
    public GameObject BulletPrefab { get; }
    public float Cooldown { get; set; }
    public abstract void SetupShot();

    public virtual IEnumerator Shoot()
    {
        while (true)
        {
            SetupShot();
            yield return new WaitForSeconds(Cooldown);
        }

    }
}
#

feels so good man 😄

languid spire
#

that aint gonna work

twin bison
languid spire
#

Shoot is a Coroutine, you cannot call a coroutine with Shoot()

late burrow
#

how to do reverse of %

twin bison
#

ah yeah yeah yeah

#

that one i knew but was an oversight 😄

buoyant knot
late burrow
#

to count how many of certain number fit in certain number

buoyant knot
#

you mean Min()

swift crag
#

that's just division

late burrow
#

full digit division

swift crag
#
x / y + x % y == x
#

i hope operator precedence goes the way I think it does

polar acorn
buoyant knot
#

still not sure what he wants

late burrow
#

fine, thought of cheaper function

twin bison
# languid spire that aint gonna work
abstract class Weapon : MonoBehaviour
{

    void Start()
    {
        Debug.Log("Start");
        StartCoroutine(Shoot());
    }

    [SerializeField]
    public float Damage;
    [field: SerializeField]
    private float BulletSpeed { get; set; }
    public GameObject BulletPrefab { get; }
    public float Cooldown { get; set; } = 1f;
    public abstract void SetupShot();

    private IEnumerator Shoot()
    {
        while (true)
        {
            SetupShot();
            yield return new WaitForSeconds(Cooldown);
        }

    }
}

This now works.
Now it #feelsgoodman 😄

buoyant knot
#

#Inspirational

#

🏅🌏🔑

languid spire
swift crag
#

the only reason to use a property there is if you want children to be able to override it

#

but then...

  • it'd need to be virtual
  • there'd be no point in serializing it
#

I suppose that children that don't override it could just leave it untouched, which would give you a serialized value for it

twin bison
#

Yep i get it now. I had it kinda like this because i wanted to understand why with getter and setter it wont show up in inspector. But now that I get.

swift crag
#

don't cross-post and don't spam

craggy oxide
#

i want you guys to double-check this to make sure im understanding correctly

#

if (Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit))

// myRay - Specifies the raycast that should be involved in the If Statement.
// out - Output: Creates a new method parameter, specifying that it returns an additional value on top of the method's default return values.
// RaycastHit hit - Creates a RaycastHit variable called "hit" (In order to store the collision data)
// maxDistance - Specifies how far away from the Raycast origin that the If Statement should apply for.
// layersToHit - Specifies which layers the raycast should interact with.

swift crag
#

None of this has anything to do with the if statement

#

Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit)

#

This calls Physics.Raycast with the provided arguments.

craggy oxide
#

but are my definitions of the "provided arguments" correct?

#

am i understanding it all correctly

#

remember that terms such as "out" and "RaycastHit" are new to me

#

i need to know that my understanding of the arguments is sound

#

if it isnt correct me

swift crag
#

ignoring the thing about if, yes, it's reasonable

craggy oxide
#

in its entirety?

#

im right about all parts?

swift crag
#

out is a keyword that passes an argument by reference so that the method can assign something into it.

#

and since you're using out, you're allowed to declare a new variable right as you use it

polar acorn
swift crag
#

rather than using a variable you declared earlier

#
RaycastHit hit;
Physics.Raycast(myRay, out hit, maxDistance, layersToHit);
Physics.Raycast(myRay, out RaycastHit hit, maxDistance, layersToHit);

Same outcome.

craggy oxide
#

Thank you.

swift crag
#

I see no reason for that to come up here.

polar acorn
swift crag
#

RaycastHit is a struct anyway

languid spire
#

yes, which can make one hell of a difference

swift crag
#

also, they live in the same scope

polar acorn
swift crag
#
if (Whatever(out var foo))
{

}

print(foo); // foo is still here
polar acorn
#

Ah, then they're the same

swift crag
#

yes it is. you can try it yourself

#
if (!target.TryGetModule<Visible>(out var visible))
  continue;

float angle = Vector3.Angle(forward, visible.entity.transform.position - from);

random example

summer stump
swift crag
#

lexical scoping rules apply as per usual

#

a somewhat ambiguous-looking case gets resolved by a compiler error

if (true)
    int x = 3; // error CS1023
#

the compiler just forbids declarations here

polar acorn
#

I didn't actually know that. I'd never thought it might exist outside the scope so any time I needed to I just defined the variable outside the if

#

Neat

swift crag
#

It'd be a chicken and egg problem

#

the variable must exist to evaluate the if expression, but it can't exist until you enter the block statement

summer stump
kindred marsh
#

kk

eternal needle
swift crag
#

sugar in the eyes of an angry compiler

twin bison
#

How can I make this

[SerializeField]
    protected Transform ShoootingPos;

To be by default the transform of the gameobject the script is attached to? Kinda like make it optional?

swift crag
#

wait, it was sinners in the hands of an angry god

#

close enough

swift crag
#

if ShootingPos is null, assign your own transform to it

twin bison
swift crag
#

yes

twin bison
#

ok thx 🙂

earnest atlas
#
private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.layer!= _playerMask) return;
    GameController.Instance.Score++;
    if (_audioClip != null)
    {
        // Play the audio clip at the specified position
        AudioSource.PlayClipAtPoint(_audioClip, transform.position);
    }

    Destroy(gameObject);
}```

When I change this from Compare tag to layer it stops working?
#

I mean its working but its not detecting player

slender nymph
#
  1. why do you need to check the layer in the first place?
  2. the layer property is not a mask
summer stump
earnest atlas
#

Omg

#

How to compare layermask?

#

or what I needed to do

slender nymph
#

why do you need to check the layer in the first place? why not go back to using a tag?

earnest atlas
#

Someone said to check for layers

summer stump
#

You can check that the layermask contains that layer. But yeah, I dunno if this is the best way

earnest atlas
#

okey will go back to tag

summer stump
earnest atlas
#

I dont understand how collision matrix setting works

summer stump
#

Just do tags

earnest atlas
#

Yeah I just reverted to tags

summer stump
#

If you need more complex functionality, also check if a component is on the object using TryGetComponent

earnest atlas
#

I have this at some places

slender nymph
earnest atlas
#

But mostly its not needed due to most of my scripts positioned on the object of interest

#

Yeah I know how access layermasks

#

I got told something about this

earnest atlas
#

Seen the setting

#

And understood nothing

#

And recently I done few changes to remove lots of GameObject.Find and still dealing with aftermath

summer stump
# earnest atlas This

You just put a checkmark where you want collisions to occur. If there is not a check where two layers line up, they will not collide

earnest atlas
#

collide like fisical collide or trigger?

slender nymph
#

both

#

actual collisions and collision/trigger messages do not happen

earnest atlas
#

Oh then im going to edit that and see what happens

#

its just build takes at this point a minute

lost sluice
#

does anyone know why this is happening? i'm following the sebastian graves tutorial for dark souls and my camera just shoots away from following the player. when i move the player the camera still moves. but why is it like this?

slender nymph
#

you'd have to show relevant !code

eternal falconBOT
lost sluice
summer stump
ivory bobcat
#

Either use a paste service to post large code blocks or inline code if it isn't too large.

polar acorn
#

!code

eternal falconBOT
vague dirge
#

Hello, how can I get the normal direction of a face ?

ivory bobcat
vague dirge
rare basin
#

define normal direction info

vague dirge
ivory bobcat
lost sluice
craggy oxide
#

How do I change the color of the collided GameObject back to it's default if it's not being raycasted onto?

rare basin
#

else

craggy oxide
#

yeah but I mean what's gonna be in the else statement

ivory bobcat
craggy oxide
#

just else return or some shi?

rare basin
swift crag
#

you need to remember the last thing you hit

vague dirge
swift crag
#

then, if your raycast either:

  • hits something else
  • misses entirely
    you can reset the color of the last thing you hit
ivory bobcat
swift crag
#

You can store the last Renderer that you changed the color of and then compare that against the Renderer that you just found

craggy oxide
#

how do i do that

swift crag
#

store the Renderer in a field so that you can access it later

craggy oxide
#

what about the comparison part

swift crag
#

just compare them with the == operator

#

or maybe !=, since we want to do something when they differ

vague dirge
swift crag
#
if (oldRenderer != newRenderer) {
  if (oldRenderer != null)
    oldRenderer.color = ...
  if (newRenderer != null)
    newRenderer.color = ...
}

oldRenderer = newRenderer;

that's the broad idea

#

that doesn't look like a real word anymore

earnest atlas
#

why null check after checking it to new renderer?

craggy oxide
#

is there a way to automatically find the color so i don't have to manually input it in, for example if there was different colored objects

swift crag
swift crag
earnest atlas
#

first check if they are null then contine?

swift crag
craggy oxide
swift crag
#

if the old renderer isn't also null

#

old renderer <-- not null
new renderer <-- null

this means we just went from pointing at a renderer to not pointing at a renderer

#

you'd get newRenderer a bit like this

#
Renderer newRenderer = null;

if (Physics.Raycast(...)) {
  newRenderer = hit.collider.GetComponent<Renderer>();
}
#

if the raycast whiffs, it's definitely null

swift crag
#

if the raycast hits, then it might become non-null, assuming the thing we hit has a renderer

vague dirge
vernal minnow
#

How can I set up a scoreboard for my enemies? They seem to be destroyed because I can do anything with them

The only fix I have in my head is having them pull the game controllers script on start so that on collision with a bullet, they add to the controllers score

swift crag
#

what will this scoreboard do?

#

is it tracking each enemy's score?

#

or is it tracking how many points the player has?

vernal minnow
#

Just shows players score

earnest atlas
#

issue comes if you have multiple levels

swift crag
#

okay, so the enemy needs to notify someone when they get destroyed

ivory bobcat
earnest atlas
#

You need DDOL object to store score to pass it between levels

vernal minnow
swift crag
#

The only fix I have in my head is having them pull the game controllers script on start

Whoever instantaites the enemy should pass them a reference to the controller, yeah

earnest atlas
honest haven
#
    {
        RaycastHit hit;
    
        for (int i = 0; i < rayCount; i++)
        {
            float angle = i * 360f / rayCount;
            Vector3 direction = Quaternion.AngleAxis(angle, Vector3.up) * transform.forward;
        

            if (Physics.Raycast(transform.position, direction, out hit, detectionRadius, _raycastLayerMask))
            {
   
                Debug.DrawRay(transform.position, direction * detectionRadius, Color.green);
                
                Debug.Log("Hit: " + hit.collider.gameObject.name);
            
                if (hit.collider.CompareTag("Player"))
                {
                    float distance = Vector3.Distance(transform.position, hit.point);
                
                    Debug.Log("Distance to player: " + distance);
                
                    if (distance < 2f)
                    {
                        _canChase = false;
                        SetState(State.Attacking);
                        PlayerController.instance.boxColliderTrigger.enabled = false;
                    }
                    else if (distance > 3.5)
                    {
                        _canChase = true;
                        SetState(State.Running);
                        PlayerController.instance.boxColliderTrigger.enabled = true;
                    }
                    break; 
                }
            }
            else
            {
                Debug.DrawRay(transform.position, direction * detectionRadius, Color.red);
            }
        }
    }``` i am inside the radius and the player has the player layer on it but not one debug is called
vague dirge
vernal minnow
vernal minnow
earnest atlas
#

!code

eternal falconBOT
swift crag
#

but I guess it would be a good way to indicate who shot the enemy. That'd matter if enemies could shoot each other without giving you points

earnest atlas
vernal minnow
#

When the enemies due, they should give points, and mostly are 1 shot (minus the boss)

earnest atlas
#

As you see I access score by accesing Instance that is static

vernal minnow
#

Wait is an instance what the clones are?

earnest atlas
#

instance is the unique instance of that class

#

Almost finished I am but Domain starts to take a minute to get anything done

summer stump
earnest atlas
#

Otherwise you will make new instance of the class each time you want to acess a value and will need to make all those values static too

summer stump
#

Unless I'm missing some context?

earnest atlas
#

Well if I know C# well enough only way you can pass same instance of class without static is by directly passing it

#

You will basically have a tree of references

vernal minnow
earnest atlas
#

Its a controller object

summer stump
earnest atlas
#

I have it dealing with Scene changes, storage, spawn on points etc

vernal minnow
#

Ah, so yours controls the spawners... hmn

#

I may have to restructure my code

earnest atlas
#

I have it control the spawn because of what I spawn

#

Also probably will spawn the portal from start because it causes a lag spike

scarlet skiff
#

i solved the problem, i saw how my structure was flawed and i solved it, this is how it is now for nayone wondering

earnest atlas
#

that "this" is irrelevant

#

this exists to differentiate variables from class and method that have same name

summer stump
lost sluice
earnest atlas
#

Instead of public transform reccomend using [SerializeField] private

Also most of these can be achivmed with transform or gameobject references

earnest atlas
vernal minnow
#

So ig I also have question 2, to pass the level, I had this (possibly ridiculous idea) of setting spawner references to the game object that added a counter for my enemies, basically they all spawn until +20 are created before quitting, and they then deactivate themselves, as all the spawners and enemies would have a trigger with the background so that the game knows when they are all dead since the game won't unlock level 2 until
First- all enemies are spawned and the spawners are done
And secondly, all the enemies are dead allowing the level 2 gate to open

vernal minnow
#

Yeesh that's more than I thought

earnest atlas
# lost sluice how do i fix it?

add void Update() (This runs every frame)
Or void FixedUpdate (runs every set time, dont know well but movements should go here)

#

Also you can use cinemamachine to make camera go after someone

lost sluice
earnest atlas
#

this is a unity method

#

that runs every frame

summer stump
#

They have FixedUpdate already

earnest atlas
#

where?

#

I dont see any

vernal minnow
#

Eh, reworded would be I'm confused on how to make an enemy detection system bc I was told that finding an object with a certain tag was laggy

summer stump
#

Line 22

earnest atlas
summer stump
earnest atlas
#

laggy is constantly searching for it

earnest atlas
#

if you search for it once in a scene its not end of the world

summer stump
vernal minnow
#

I just don't know how to prevent it from breaking when it no longer finds an object

earnest atlas
earnest atlas
#

add them to that object as children

#

Basically most of commands that are not GameObject.Find() are not really coputation heavy at least at beguinner levels

lost sluice
vernal minnow
modest dust
earnest atlas
#

also that

#

tho reference not gonna be of much use

#

unity wont automatically set object as null

modest dust
#

Didn't read everything so I don't know the exact context

earnest atlas
#

you can tho save amount of created enemies into variable in DDOL class with public variable and minus the dead ones

vernal minnow
earnest atlas
#

when it dies just minus 1 from there

#

and when it reaches 0 you can just load next level

modest dust
vernal minnow
earnest atlas
#

just do same as adding them

#

instead of ++ do --

#

If health is not going to start working soon my brains gonna melt

vernal minnow
earnest atlas
#

how do you kill an enemy?

#

just access the variable from there

#

it doesnt matter from where what matters is the count

vernal minnow
#

The bullet collides but in doing so, destroys itself before sending back the object it hit

summer stump
# lost sluice i'm not sure. i was just following the tutorial

If you're not sure, you need to go back and follow the tutorial again until you know.
Sebastian Lague tutorials are a bit higher level, and considering you asked which line Update should go on, I think you may need to go and do some more basic tutorials first.
Have you gone through the Unity pathways yet? That should be the first thing you do
👇
!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

earnest atlas
#

literally it matters not

modest dust
vernal minnow
earnest atlas
#

You dont need reference

#

Just call it when its killings something

#

this is pros of singleton class

vernal minnow
#

Then how would it know that a count even exists?

earnest atlas
#

It does not needs to

#

Literally just
if(hitenemy)
SingletonClass.Instance.Count--;
CommitDieOther
CommitDieMe

#

when you create an enemy just do this
Instantate(enemy)
SingletonClass.Instance.Count++

vernal minnow
#

Hold up, are all of my variables singletons?

#

I feel like I use public static alot

#

Just looked up singletons bc I've never heard the term before

modest dust
# vernal minnow I feel like I use public static alot

Here's a delegate solution of how you could do it.

public class Spawner : MonoBehaviour {
  [SerializeField] Enemy m_enemyPrefab;  
  private int m_counter;

  public void Spawn() {
    ++m_counter;
    Instantiate(m_enemyPrefab).Init(OnEnemyDeath);
  }
  
  public void OnEnemyDeath() {
    if (--m_counter == 0) {
      // Unlock level
    }
  }
}

public class Enemy : MonoBehaviour {
  private Action m_onDeath;

  public void Init(Action onDeath) {
    m_onDeath = onDeath;
  }

  public void Kill()
  {
    m_onDeath?.Invoke();
    Destroy(gameObject);
  }
}
#

Using events is also a good solution I suppose

vernal minnow
#

Objects have an on death action?

rustic rapids
#

can someone help me with visual studio? I've downloaded the unity game dev download but every C# file that I open from unity gets this miscellaneous files assembly instead of the csharp one and I cant find a way to change it

earnest atlas
#

yeah thy do

eternal falconBOT
earnest atlas
#

OnDestroy()

rustic rapids
lost sluice
earnest atlas
#

its probably because it also takes camera position values before

#

at least in tutorial I seen before that was an issue

lost sluice
#

i've zero'd each of them like 5 times and it still doesn't work

earnest atlas
#

you put in the Scene object not prefab?

lost sluice
#

regardless of whichever one i do it does the same thing

earnest atlas
#

Im way to tired atm. Have u posted the code?

lost sluice
#

yes it's above

earnest atlas
lost sluice
#

yes

earnest atlas
#

Box save this guy pls

#

My unity crashed just great

ashen wind
#

you know in games where you place a building and the unplaced building hovers over your cursor until you click

#

I'm doing that, and the following code is supposed to make the unplaced cursor building snap to the grid cell that it's over

#
        Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);        
        Vector3Int cell_coords = gs.tilemap.WorldToCell(cursorPos);       
        transform.position = gs.tilemap.CellToWorld(cell_coords);
#

the problem is, there's some kind of offset

#

the final transform position that gets set is wrong and ends up misaligned with the grid

#

I'm worried it's related to the fact that grid cells have their transform.position point in the top left

#

and the building has it in the center

vernal minnow
#

@earnest atlas @modest dust thanks for your help fellas

clear seal
#

is that logic?

#

if the player trigger the canon

#

it will start the update

#

then the update will wait until the shoot is ended and it will repeat?

#

right?

polar acorn
# clear seal

Update runs every frame, which means the IsCoolDown coroutine starts once per frame.

In OnTriggerEnter, if this collides with something tagged player, it'll start a coroutine. This coroutine will check if the F key was pressed this frame. If it does, it does a bunch of stuff including a wait of 1.25f. If the key was not pressed this frame, the coroutine waits 4 seconds, does nothing, then ends

ashen wind
#

won't that create a new coroutine every single frame?

ashen wind
polar acorn
ashen wind
#

oh gotcha

#

@clear seal update doesn't need to be triggered

#

it'll call constantly as often as it can

clear seal
ashen wind
#

so you just want it to shoot if it's off cooldown and not shoot if it's on cooldown?

ashen wind
#

you can use coroutines for that, but I find it's typically simpler to just use a timer

#

lemme give an example

#
public float cooldownTime = 1f;
private float cooldownTimer = 0f;


 
  void Update()
    {
        if (cooldownTimer > 0)
        {
            cooldownTimer -= Time.deltaTime;
            if (cooldownTimer < 0)
                cooldownTimer = 0;
        }

        if (Input.GetKeyDown(KeyCode.F) && cooldownTimer <= 0)
        {
            Shoot();
            cooldownTimer = cooldownTime;
        }
    }

    void Shoot()
    {
       // shoot code goes here
    }
polar acorn
#

If you want to use coroutines it's a simple matter of setting a bool to false, then starting a coroutine that has a wait, then sets that bool to true

timid saffron
#

are the codes written in junior programmer unity courses well optimized codes or are they like the codes from beginner youtube tutorials that are poorly written for people to understand easier

polar acorn
#

if it's true, you can shoot

ashen wind
#

since waitforseconds does this same thing in one line

polar acorn
#

Remember that Coroutines are Co routines. They run alongside the rest of the code. Nothing will wait for a coroutine to finish, so having the last line of a coroutine be a wait is 1000% pointless

ashen wind
#
   
 void Update()
    {
        if (Input.GetKeyDown(KeyCode.F) && canShoot)
        {
            StartCoroutine(ShootWithCooldown());
        }
    }

IEnumerator ShootWithCooldown()
    {
        canShoot = false;
        Shoot();
        yield return new WaitForSeconds(cooldownTime);
        canShoot = true;
    }
summer stump
#

Phone coding is too slow again. Almost had it done haha
Do it like that goldwerdz☝️

ashen wind
#

I'm pretty sure it's the pivot, but it could be something with the CellToWorld function rounding or some nonsense like that

#

the only thing that makes me think it's not the pivot is that I tried with a gameobject that has a transform instead of a recttransform and it's still off

potent echo
#

Hey guys, I wrote a script EnemyController (https://gdl.space/inijebuyap.cs) and within it there exists the ShootBullet method. This method instantiates a bullet (BulletScript: https://gdl.space/fikoluxawa.cs) and sets it's moveDirection based off which direction the Enemy is facing. This works fine when there's only one instance of an Enemy, but when there are more (and are both facing the player from different sides), they both start shooting in the wrong direction.

fierce shuttle
# timid saffron are the codes written in junior programmer unity courses well optimized codes or...

Do you have an example of code from that course you are concerned about? Also can you elaborate on what you mean by "optimized"? Usually there are many ways to solve a problem, and later on architecture can play a role in helping with that too, though optimizing usually suggests a concern with performance such as low framerate, memory management, rendering draw calls, etc, unless your referring to something else?

teal viper
ashen wind
#

this is 2d

teal viper
#

And the camera is set to orthographic and has 0 rotation?

ashen wind
#

correct

teal viper
#

Try drawing a ray at the world position of the cursor.

#

Or some other gizmo

timid saffron
#

so i try to learn it right from the start

#

so is unity junior programmer a good place for this?

teal viper
#

Thing is, you're not supposed to stay on the level you learn as a beginner.

#

Your knowledge/understanding and coding skills in general are supposed to improve over time.

#

It's fine to write unoptimized code and use bad practices at first, but you'll learn better coding with time and experience.

summer stump
teal viper
#

The problem with the tutorials is that they give you partial understanding for the sake of achieving a specific mechanic or even plain out hand you the implementation on the plate without you actually learning anything in the process

#

That's why a systematic course like the unity pathway one is better.

clear seal
ashen wind
ashen wind
#

in the coroutine, it'll be set to false after you shoot, then the coroutine waits for the cooldown, then it sets it to true

clear seal
ashen wind
clear seal
ashen wind
#

it will continue running in the background until the waitforseconds is done

#

the whole point of coroutines is that they don't end, they wait in the background for something

#

and then once that happens, they can end

#

but the rest of your code still runs while the coroutine is waiting

clear seal
#

but from what i have understood is

#

can shoot false => shoot => wait => can shoot true right?

ashen wind
#

and notably the other functions like update are continuously being called while wait is happening

clear seal
#

explain like i was a little kid cuz i dont understand

#

pls

ashen wind
ashen wind
#

it's kinda like a clock that ticks every second

ashen wind
#

except a frame usually ticks like 30 or 60 times per second

#

based on how fast your computer can run code

#

it varies

ashen wind
#

every time a tick happens, unity will call the Update() funcition, and any code you put in update will run

ashen wind
#

so that's why we put the code that checks if you hit the f key and then shoots in update, so it's checking as fast as it can for whether you pressed it

ashen wind
#

typically, code can only do one thing at a time. it runs each line of code in order. this creates a problem, because if we want it to wait 10 seconds, it will have like 600 frames where it's not running any code and your game will just be frozen

ashen wind
#

so there's two ways to get around this problem. the first is just to write down the time that has passed in update and only allow the player to fire if the time that has passed since we started writing it down is bigger than 10 secs

ashen wind
#

just writing down how much time has passed by subtracting from the cooldown how much time has passed since the last tick

clear seal
#

hold i will be back just going to unity deltatime learn video

ashen wind
#

ok

clear seal
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ashen wind
last grove
#

can someone help me with vscode

timid saffron
#

@teal viper@summer stumpthanks. thanks to you I finally feel relieved following something about learning coding on internet 🙂 (as someone who followed youtube tutorials for 3 months when I was using gamemaker and I couldnt do anything after the tutorials)

summer stump
eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

last grove
last grove
last grove
#

now I can't fix it

summer stump
teal viper
last grove
ashen wind
#

it's got a rect transform because it's attached to the canvas, and i thought that might be the problem

#

but I remade the gameobject from scratch as a regular gameobject

#

and the same exact thing happens

summer stump
last grove
#

if I open a different file then it will use that one

teal viper
summer stump
#

Well I dunno. But since this is not a Unity issue, I don't think I can continue with the off-topic. Sorry

last grove
#

fair enough. thanks for the help

teal viper
clear seal
#

uhh i dont understand

#

is this good

meager raptor
#

i hid this but now i cant seem to get this back up (had to find a yt vid to show this) where can i turn this back on?

clear seal
ashen wind
# clear seal

can you copy paste this as text? it's hard to read as a screenshot

clear seal
ashen wind
#

!code

eternal falconBOT
ashen wind
#

backticks

#

if the bot zaps it cause it's too large, paste it in hatebin

clear seal
#
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 100;
private bool IsCoolingDown = false;

public AudioSource CanonShot;
public ParticleSystem CanonMuzzleFlash;

public float cooldownTime = 1f;
private float cooldownTimer = 0f;

void Update()
{
    if (cooldownTimer > 0)
    {
        cooldownTimer -= Time.deltaTime;
        if (cooldownTimer < 0)
            cooldownTimer = 0;
    }

    if (Input.GetKeyDown(KeyCode.F) && cooldownTimer <= 0)
    {
        Shoot();
        cooldownTimer = cooldownTime;
    }
}

/**void OnTriggerEnter(Collider Player)
{
    if (Player.tag == "Player")
    {
        Debug.Log("canon shot");
        StartCoroutine(Shoot());
    }
}**/

/**IEnumerator Shoot()
{
    
    if (Input.GetKeyDown(KeyCode.F))
    {
        IsCoolingDown = false;
        yield return new WaitForSeconds(1.25f);
        CanonShot.Play();
        CanonMuzzleFlash.Play();
        Vector3 shootD = (bulletSpawnPoint.forward + bulletSpawnPoint.up * 2).normalized;
        var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
        bullet.GetComponent<Rigidbody>().AddForce(shootD * bulletSpeed, ForceMode.Impulse);
        Debug.Log("coroutine executed");
        IsCoolingDown = true;
    }

    yield return new WaitForSeconds(4);
}**/

void Shoot()
{
    //yield return new WaitForSeconds(1.25f);
    CanonShot.Play();
    CanonMuzzleFlash.Play();
    Vector3 shootD = (bulletSpawnPoint.forward + bulletSpawnPoint.up * 2).normalized;
    var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
    bullet.GetComponent<Rigidbody>().AddForce(shootD * bulletSpeed, ForceMode.Impulse);
    Debug.Log("coroutine executed");
}```
summer stump
ashen wind
#

that looks right

#

this could be an else:
if (cooldownTimer < 0)

#

but that's just style

#

it should function properly

clear seal
#

ok

#

i will test

ashen wind
clear seal
#

work?

#

the way i did?

ashen wind
#

I find using timers to be more beginner friendly because you can see what the code is doing

#

but the community prefers coroutines, probably because too many cooldown timer variables can clutter up your code and make it confusing to read

clear seal
fierce geode
#

Anyone got any piece of advice for moving along normals? I'm trying to make a character that can move around a vertical loop, it works all good until he reaches the part of the loop that sticks vertically upwards, then he starts moving downwards; it happens even with no gravity so my best assumption is that it has something to with how the velocity is being applied to the rigidbody,

currently, I multiply the left and forward velocity by the transform.rotation.
The only things I do with the transform rotation is rotating it so that it sticks upwards following the normal of the ground using Quaternion.LookRotation.

clear seal
ashen wind
#

basically the concept that computers can only do one thing at a time

ashen wind
#

and coroutines are a special workaround to get around that limitation

#

so it's effectively like multiple computers are running side by side in your computer

clear seal
ashen wind
#

but if you look on the internet about threading I'm sure there are good explanations somewhere

clear seal
ashen wind
#

and as you can see, it's super offset

#

reposting my question cause I'm still super confused:

you know in games where you place a building and the unplaced building hovers over your cursor until you click
I'm doing that, and the following code is supposed to make the unplaced cursor building snap to the grid cell that it's over


        Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);        
        Vector3Int cell_coords = gs.tilemap.WorldToCell(cursorPos);       
        transform.position = gs.tilemap.CellToWorld(cell_coords);

the problem is, there's some kind of offset
the final transform position that gets set is wrong and ends up misaligned with the grid

ashen wind
#

and for some reason the CellToWorld function is spitting out coords that make no sense

#

oh nvm, i fixed it

#

it was a combination of the tilemap being offset from the parent grid and the rect transform having the pivot in the center

#

the two bugs teamed up and made it take way longer to solve

sharp stirrup
#

is setting a game object through a public variable in the ui faster than transform.Find()? or is there no difference at all. i imagine it would be

gaunt ice
#

Setting reference is mush faster than find

#
sharp stirrup
#

okay thats what i thought. i wasnt sure since it was done through the ui idk why i thought it might be slower lol thanks

soft wren
#

dc.rotateDuck(new Vector3(FirstPersonController.Instance.transform.position.x, dc.transform.position.y, FirstPersonController.Instance.transform.position.z) - dc.transform.position);
This may sound like a stupid question but I can't figure it out for some reason. This piece of code rotates the enemy towards the player. How would I rotate it away?

#
public void rotateDuck(Vector3 direction)
{
    Quaternion rotation = Quaternion.LookRotation(direction);
    transform.rotation = Quaternion.Lerp(transform.rotation, rotation, rotateSpeed * Time.deltaTime); 
}

This is how it rotates ^^

eternal needle
soft wren
eternal needle
# soft wren What do you mena the lerp isnt really a lerp?

Lerp = linear interpolation. T should be a value going from 0 to 1, while yours is just a constant (simplifying here since deltaTime is not a constant itself). The value is going to relatively be very small but let's say around speed * 0.01f at all times.
You want to use RotateTowards because you can have it rotate at an exact speed, while not overshooting.

#

With your lerp, you cannot guarantee it will move at a certain speed. If the difference between A and B is larger, it will rotate faster

soft wren
eternal needle
#

It's possible to do with vector3 but then you have to construct the quaternion afterwards anyways

soft wren
#
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotateSpeed);```
#

so like this?

#

I have to convert the vector3 of the direction to a quaternion anyway

eternal needle
soft wren
eternal needle
swift crag
soft wren
#

Ahh so if i made the speed value 180 it would take 2 seconds to rotate 360 degrees

eternal needle
soft wren
#

Thanks for your help :), everything is working as intended now

fierce shuttle
# sharp stirrup okay thats what i thought. i wasnt sure since it was done through the ui idk why...

Setting it through the ui or even a static class/singleton wouldnt be a barrier for speed, since a reference is stored in memory you always have direct access to it, whereas any "Find" call has to search a collection (your scene hierarchy for example) and check "is this index the thing your looking for?", (hopefully) eventually find the object and then return it, assuming you cache the reference after its found, then the speed difference would more-or-less be the same, but a direct reference in the UI means the initial search never needs to happen anyway

mighty falcon
#

yo

#

when inside of a script how do you referance the game object the script is a child of

swift crag
#

the transform property gives you your parent

#

and you can ask for the gameObject property from that Transform

mighty falcon
#

where should i start looking

#

to make an overlay that is locked to the camera

slender nymph
#

use a screen space overlay canvas

mighty falcon
#

actually now that im thinking about it i would rather have the text dialogues appear infront of the npcs

slender nymph
mighty falcon
#

is there a gameobject that contains text

#

you could also just tell me

#

but sure ill go spend 15 minutes googling and finding unhelpful information until im lucky enough to stumble apon something i can use

#

nvm

slender nymph
#

if it takes you 15 minutes to find any information about how to display text in unity then you really need to get better at using google. this discord is not a substitute for learning or using google, it is a supplement

mighty falcon
#

i just noticed the "legacy" in the ui thing which should solve my issues

eternal needle
#

This also isnt a code question

vernal minnow
#

How do you code audio into your game?

#

I'm assuming the audio components need something to let them work

slender nymph
#

wdym by "need something"? they can JustWork™️

vernal minnow
#

I can just add the file and they'll work when the game starts?

#

Alr, and how do you destroy an object (a gamecontroller) after its been set to don't destroy on load?

slender nymph
#

pass it to the Destroy method

vernal minnow
#

Sweet

rare urchin
#

why i cant drag Text UI to Code?

rich adder
rare urchin
#
using UnityEngine;
using UnityEngine.UI;

public class ButtonTextChanger : MonoBehaviour
{
    public Text textUI; 
    public string newText = "New Text"; 

    void Start()
    {
    
        if (textUI == null)
        {
            Debug.LogError("Text UI is not assigned!");
        }
    }

   
    public void OnButtonClick()
    {
       
        if (textUI != null)
        {
        
            textUI.text = newText;
        }
        else
        {
            Debug.LogError("Text UI is not assigned!");
        }
    }
}
summer stump
#

If it is TextMeshPro, add
using TMPro
to the top of that script, and change the type from Text to TMP_Text

rare urchin
#

cuz it not my code

#

i just told chat to make code that when im click button just change Text on Text

summer stump
rare urchin
#

im not good about code

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rare urchin
#

it my project that i wanna create game

#

and almost over now

#

sry about that

#

but i dont have time

#

ty

summer stump
#

"But either way, you can show us what we need to confirm the issue, or continue on with whatever you want"
Can't help if you don't show us what was asked for

vale karma
#

do you guys know any good vids about state machines? I am tryin to find a good vid but every one i found the comments are saying "no thats wrong do this" or "its better this way".

summer stump
summer stump
# rare urchin here

How is that the inspector of the object?
That is you saying something
Which is not what was asked for

rare urchin
#

it just Text and Button

summer stump
vale karma
#

okay ill checkem out

rare urchin
rare urchin
#

i just want to click that white button and change text on score

vale karma
#

loll i was actually watching one of his vids @rich adder why does he have multiple state machine tutorials? im guessing the most recent one is the best?

#

I watched the second one twice

summer stump
rich adder
summer stump
#

The inspector is blank

rare urchin
#

it just defualt

vale karma
#

okay, Ill follow it, alot of new concepts i understand but cant code yet

summer stump
rich adder
summer stump
vale karma
vale karma
#

I dont know what most of it means yet so i always say "oh i shouldnt need that" and end up stumping myself

summer stump
#

That's it

#

Text is for the legacy text component

#

You are using TextMeshPro, which is different, and cannot be referenced as Text

vale karma
#

After i finish movement, what kind of concept should i learn next?

rare urchin
#

ty

timber tide
#

advance movement

vale karma
#

:0 whaaaa

ivory bobcat
#

Make/release a complete game - it doesn't matter how mediocre it is. Then focus on improving/substituting individual parts like hud/ui and whatnot, knowing that the game is at least complete already. Follow a tutorial if necessary.

tall storm
#

How can I get my enemy to go after the players position and if it touches the player then the player loses a life and the enemy dies

vale karma
#

If I make a few scripts for a state machine, should i make another script to get the input from the new input system? or should I split up the inputactions into there respective state?

eternal needle
tall storm
vale karma
#

Okay, ill try it out

eternal needle
tall storm
#

alr

#

thanks

tall storm
#

Yo i kinda need some help again, I made the enemy move and stuff like that and now that i made a script to take out the players health i get this error

#
private void OnCollisionEnter(Collision collision)
{
    if (collision.transform.tag == "Player")
    {
        Destroy(gameObject);
        playerLogic.GetHit(1);
    }
}``` error is at playerLogic.GetHit(1);
tall storm
#

no, it isnt

#

PlrLogic playerLogic;

rich adder
#

error says otherwise

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

public class PlrLogic : MonoBehaviour
{
    public float health = 3;

    public void GetHit(float damage)
    {
        health -= damage;
        if (health <= 0)
        {
            Application.Quit();
        }
    }
}
#

this is PlrLogic

rich adder
tall storm
#

in the enemy script

rich adder
#

thats not assignment

#

thats declaring

charred spoke
#

I love the if health 0 or less just quit the whole damn game

tall storm
#

and how to i assign it

rich adder
tall storm
#

by dragging the player

#

oooh

rich adder
#

then do the same thing

tall storm
#

it doesent let me drag it in

rich adder
tall storm
#

whats a prefab

rich adder
#

screenshot it

tall storm
#

alr

slate haven
#

Hi, I am facing a strange issue, I basically want to Move the road (lane) towards a position after getting instantiated. So In the following LaneIncrease(), isLaneMoving bool becomes true, and so does the instantiatedLane gameobject gets assigned a prefab. But in the Update(), it doesnt get updated. I always get isLaneMoving = false, and therefore my lanes are unable to move.
Image
Image
The function LaneIncrease() is called by picking up an item, which itself has a script called PickupManager(), it calls the method of LaneManager by referencing

rich adder
#

you have to drag the gameobject with that script

tall storm
#

ooh i think i did it

rich adder
tall storm
#

u told me to drag the gameobject

rich adder
#

if its a player script why did you put it on enemy

tall storm
#

idk

#

wait

#

im stupid lol sorry

#

i had to drag the player in the player logic

#

thanks

#

but the game doesent quit when 3 enemies touch me

charred spoke
#

Application.Quit does nothing in the editor

#

You either want to exit play mode or do something else

tall storm
#

ok thanks

lean basin
#

excuse me, why did my character stopped at that specific spot? it makes no sense.
The specific spot it looks like... in the edge of ... that thing.

rich adder
tepid summit
#

holy shit

#

unity does have vector4

#

its for colors

#

which makes sense

#

a color is RGBA

#

a vvecrtor 4 would have 4 inouts

charred spoke
tepid summit
#

i know what it is

lean basin
tepid summit
#

jesus

vale karma
#

i see the problem

#

it aint got no gas in it

#

if I already created a full script with only 1 bug in it, should I keep the script and change it to add a state machine or should i redo it from scratch but use it as reference?

acoustic sun
#

I am having issues with my coding. On Unity, its saying I made some mistakes but I am not able to identify the issue on Visual Studios

rich adder
rich adder
#

configure your IDE first

vale karma
#

@lean basin i think you have the same friction issue i do, have you added a physical material to your rigid body?

acoustic sun
#

Im trying to figure out how to configure it. I'm looking everywhere to find resources but so far, no luck

eternal falconBOT
vale karma
#

and do you get caught on it when your jumping?

rich adder
#

Click it

#

I suggested you temporarily remove the script with errors before doing the config so everything compiles properly @acoustic sun

#

do you understand how to do that ?

lean basin
north kiln
#

Then you can uncomment your code and fix your (now highlighted) errors

rich adder
acoustic sun
#

I checked on there, pretty much I did everything on there

north kiln
#

Is that a "pretty much", or a "I did"

acoustic sun
#

I did

north kiln
#
  1. Making sure the external tools setting is set in Unity.
  2. Making sure the Game development with Unity workload is installed.
  3. Make sure you have no compiler errors by commenting out your code and letting it compile.
  4. Try restarting VS by reopening it with Unity's menu: Assets/Open C# Project
acoustic sun
#

For 4. Its letting me reopen it with the unity menu

#

Am I supposed to get Github as well for this?

lean basin
# rich adder there is a lot going on here.. Start debugging also I would do some ray checks m...

hmm, there are no invisible collider.
I'm not sure what else to debug.
The character is on ground and is in running state and doesn't change at all, there is not really much going on, it doesn't even call SnapToBottom()

The specific spot where the character stopped and seem to be trying to shove it's body to the ground is when it's hitting half wall? like a wall in the front it that is not high enough.

teal viper
#

Or anyone for that matter. So, no.

acoustic sun
#

Okay because I am getting GitHub Copilot norifications on my script

rich adder
rich adder
#

did you Debug.Log yourisGrounded

#

the built in CC one is kinda ass

#

would double check // Snapping logic also

#

also not sure what you mean by

I'm not sure what else to debug.
there isn't any debugging in here xD

eternal needle
lean basin
# rich adder You tried another scene ? is it only that spot or just any edge?

any edge that is in similar shape.
Hmm I tried to debug isGrounded (i mean the CollisionFlag) it stays grounded except when going downhill in a big slope but the code is stuck when Im going uphill.

unfortunately the SnapToGround() didn't get called at all during the time it got stuck. so... the snapping logic is not called.
But I tested the snapping logic, it worked as expected, it doesn't switch grounded state at all when the slope is not that big.

lean basin
eternal needle
#

You would have to implement it by checking what object is in way, then project your movement

#

Honestly when trying it myself, it was still buggy or annoying in some odd cases. Your best bet is really just use an existing solution like KCC or just use rigidbody movement.

eternal needle
#

It definitely will take some learning to use, I dont even use it because I just wanted to setup something less bulky. I opted to just use rb movement

lean basin
#

that looked more interesting than the link I posted. Thank you for your suggestion!

vale karma
#

is it easier to manipulate my code with 1 bug in it to a state machine or should i start from scratch?

teal viper
vale karma
#

im just makin a new one with a reference

#

whats a better word than 'look

#

public Vector2 MovementAction { get; private set; } is this a class or a variable?

twin bison
#

Hi guys.
I want to check in a OnTriggerEnter2D if the collision is in specific layers.
I found this post https://discussions.unity.com/t/using-layermask-in-ontriggerenter/216825
But this won't work.
LayerMask.NameToLayer isnt what i want because I already have the layers to check against in a _collisionMask variable.
The second answer also doesn't work:

void OnTriggerEnter2D(Collider2D other)
    {

        if ((_collisionMasks.value & (1 << other.gameObject.layer)) > 0)
        {
            _health.TakeDamage(10);
            print("Hit");
        }
    }

Ok the second answer works now. I don't understand the code and it feels a bit hacky. Is this a good way? Basically I want to create an all purpose Hurtbox I can attach to enemy or player and only collide with things I want to specify. For example the player should not collider with its own bullets.

eternal needle
nimble scaffold
#

Errow :- Assets\MyMadeScripts\RaceScene.cs(11,30): error CS0122: 'TimeTrialManager.EndTimeTrial()' is inaccessible due to its protection level

code =

using UnityEngine;

public class RaceScene : MonoBehaviour
{
    public TimeTrialManager timeTrialManager;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("FinishLine"))
        {
            timeTrialManager.EndTimeTrial();
        }
    }
}
eternal needle
nimble scaffold
barren aurora
#

can anyone help me, to understand a "Github Use Documentation" ?

it s only 2 Lines, but i do not understand what to do

#

( JAva )

eternal needle
barren aurora
nimble scaffold
#
using UnityEngine;
using UnityEngine.UI;

public class TimeTrialManager : MonoBehaviour
{
    public Text timerText;
    public float timeLimit = 300; // Set the time limit in seconds

    public float elapsedTime;

    void Start()
    {
        UpdateTimerDisplay();
    }

    void Update()
    {
        if (elapsedTime < timeLimit)
        {
            elapsedTime += Time.deltaTime;
            UpdateTimerDisplay();
        }
        else
        {
            EndTimeTrial();
        }
    }

    void UpdateTimerDisplay()
    {
        timerText.text = "Time: " + FormatTime(elapsedTime);
    }

    string FormatTime(float timeInSeconds)
    {
        int minutes = Mathf.FloorToInt(timeInSeconds / 60);
        int seconds = Mathf.FloorToInt(timeInSeconds % 60);
        return string.Format("{0:00}:{1:00}", minutes, seconds);
    }

    void EndTimeTrial()
    {
        timerText.text = "Time Trial Finished!\nElapsed time: " + FormatTime(elapsedTime);
        // Add any additional logic for time trial completion
    }
}
eternal needle
nimble scaffold
#

all are public

eternal needle
#

No they arent, it is private by default

barren aurora
twin bison
barren aurora
nimble scaffold
#

ok

barren aurora
# nimble scaffold ok

try again, should work.
remember

Everything what is NOT Public, can be NOT acessed from outside!

nimble scaffold
#

ik

#

hey bro the error is still there

#

Assets\MyMadeScripts\RaceScene.cs(11,30): error CS0122: 'TimeTrialManager.EndTimeTrial()' is inaccessible due to its protection level

#
using UnityEngine;

public class RaceScene : MonoBehaviour
{
    public TimeTrialManager timeTrialManager;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("FinishLine"))
        {
            timeTrialManager.EndTimeTrial();
        }
    }
}
burnt vapor
eternal needle
#

Just curious, is your ide configured? Also save your other script

nimble scaffold
#

i use sublime text

eternal needle
#

This is why we dont spoonfeed answers 😅

#

Ok well, dont

#

Use a real IDE

nimble scaffold
#

vs code

burnt vapor
#

Please use a proper !ide for using Unity, we can't/won't help users without a misconfigured IDE

eternal falconBOT
barren aurora
# nimble scaffold ik

my foult. Was because i am in other things with my mind.

   public  void EndTimeTrial()
    {
        timerText.text = "Time Trial Finished!\nElapsed time: " + FormatTime(elapsedTime);
        // Add any additional logic for time trial completion
    }
burnt vapor
nimble scaffold
#

now i saves both the scripts

eternal needle
burnt vapor
#

And there you have it, the suggestion was completely ignored since the initial issue is now resolved

barren aurora
nimble scaffold
#

suiiiiii

#

the error is gone

burnt vapor
#

Lack of syntax highlighting, no proper error handling by the IDE, no quick fixes by the IDE

nimble scaffold
#

thanks to @barren aurora and @eternal needle

eternal needle
barren aurora
# eternal needle <:notlikethis:1068134558123442236> stop spoon feeding too. The guy didnt even un...

Maybe.
BUT

i start same way.
You learn by doing.

Did you ever think about, that the Situation to put "Content" in TONS AND CONTAINERS into the Mind of a Guy who only want to know, how to fix an error

is contra Productive ?
if he want to stay, and countinue, and to better up his skill, he will learn.
but you do not help him, for a singel short Question, if you "Pusch 1000Ths Sides of Code" inside his mind, for such a small question.

this bring ppl to go away, not to learn things
here is best Example.

i startet, with the Question "how to collect a trigger"
and be BOMBED with 10 000 C# Books ( i never read )
Today, i am in since 8 Years, i am C# Pro, and have much complicatet Unity Projects.

BUT I WOULD NEVER START TO READ 10 000 Side Documentations
For a short Question!

burnt vapor
#

That's a lot of words

#

The problem is that rather than explaining the problem you just give the updated code as-is, without explaining what went wrong

#

That's not learning

eternal needle
#

If someone goes away by the idea of having to learn, they are not cut out for coding. That is the reality of it

barren aurora
burnt vapor
#

I have a hard time reading this, sorry

eternal needle
#

None of that makes sense yea

north kiln
#

!warn 892828741443674192 As you have been told previously, you need to have a configured IDE to get help here. Sublime text is not a valid IDE. You can use VS Code, Visual Studio, or JetBrains Rider.

eternal falconBOT
#

dynoSuccess electro_op has been warned.

eternal needle
#

It was clear he thought methods were public by default, but now he wont learn otherwise.

north kiln
#

Luckily for everyone, if that happens they will be muted

barren aurora
north kiln
#

Nobody is asking them to read 10 books and look at millions of tutorials

#

they're being asked to configure their IDE and learn the basics

barren aurora
# eternal needle You told him an incorrect answer. He used it. Error didnt fix. He came back, cle...

Yes, the first mistake was mine. I set the wrong method public.

My goodness, this is the beginner channel.
YES ! as a pro you always say. learn it right.
But you want to have fun with Unity first, not study 10,000 documentations.

He probably imported an asset and it has an access error. If he keeps at it, he will learn. But overwhelming him with books and confusing documentation is the opposite of fun.

Get something right first.
Then see where the problem lies.
How many get in and are out again after 2 weeks?
Does everything always have to be so doctrinaire? that's ... very fun-killing.
Especially with such a simple request, it's not a complex script. You helped him faster than you explained the documentation to him. hm ?

Stay human, always a good choice

💪

barren aurora
# north kiln Nobody is asking them to read 10 books and look at millions of tutorials

Yes, I understand you too.

We've all been through it at some point.
You know, I started with Udemy.
in the first "WEEK!" Toturial, I didn't know how to take 10 arrows from another collider. It wasn't explained there.

Then, when I asked in a forum, they all hit me with half 10 year courses. That is: absolutely counterproductive! Today I have extremely complex projects, so comprehensive that you wouldn't even want them to be true.

I learned everything myself.
But nobody has been able to help me with a book. You have to gain experience first. This : is the start.
You can turn a blind eye to that, can't you?

NOTE: nobody new even knows what an IDE is.
Even I don't know that.
just as a remark, and my things work wonderfully...

arctic ibex
#

!codeblocks

eternal falconBOT
burnt vapor
#

Also, the whole issue was related to a basic c# feature and not Unity. Stuff like these should be know if you start with Unity. Beginner Unity is not beginner c#

#

Stuff like this can be learned from tuts that can be found in the pinned messages

vale karma
#

is using localEulerAngles better than localRotation = Quaternion.Euler?

languid spire
#

they are identical

lean basin
# tepid summit no colliders?

no Collider in the character object. CharacterController provide it's own capsule collider which we can't edit like normal Collider

eternal needle
north kiln
barren aurora
# north kiln > NOTE: nobody new even knows what an IDE is. > Even I don't know that. > just a...

Yes, but only.
It's a newcomer! Don't make such a big elephant out of it.
I don't use "IDE" for me it's Unity Editor, and Visual Studio. That's it. I don't like abbreviations.

and overall, he could save his script, and he was helped. So he seems to have a working IDE.

But good now. I helped him, why don't you stone me for it? A community where someone helps someone new. How can he.

Let's hit him with rules, requirements and compulsory events that he'll never understand as a new member, so that we can have fun and he's not helped.

And now: stone those who help a newcomer.
Hail community, the master has spoken.

In all seriousness and without irony: I'm off again, I've got other things to do.

rare basin
#

just doesnt make sense

#

i don't use IDE - i use Visual Studio 🤔

icy grotto
#

hi, can this one be converted to a Ternary operator?

rare basin
#
act1SkillImgs[0].color = skillUnlocked1 ? Color.white : lockedColor;
north kiln
barren aurora
# rare basin what you said

Short: i use VStudio, this IS an ide, BUT i dont call it this.

nobody knows this "Short words"
here in germany we tell this DBDBHKP
also nobody know.

rare basin
#

everyone knows what an IDE is

#

what are you talking about

north kiln
#

I do not use visual studio

#

Others don't either, hence we use the word that refers to the group

rare basin
#

every programmer that knows the basics, knows what an IDE is (well even not programmers)

barren aurora
#

@rare basin @north kiln

Shortly:
The question was awnsered.

and i have other things to do, than to talk about IDE or not IDE,
or to waste my time, with "rules" for nothing.

it was just 1 word to change
the problem of the guy is solved.

That s it.
it is that easy, truly. it is.

rare basin
#

Then stop talking about it rather than constantly saying you are "out" but yet you aren't

north kiln
#

Go away then, please

barren aurora
# north kiln Go away then, please

just i was away, you did start again.

Just; it s completly not senceful, to discuss how about to call an IDE,
it s not simple.
it just wastes time.

and also all what i did say:
it was 1 word to change
no need, to avoid to help others, just because they should read tons of sides.
This is not nice for a noob.

stay familiar
and be nice guys.
This is just a noob, want to play around with Unity.
maybe, he can stand by us, or you make him crazy with 10 000 rules
and he stop.

think about.

west sonnet
#

What's the best way for me to use a random sound clip when something is triggered? I don't want my enemies punches to all sound the same. This is what I've got at the moment, but it's only player the first clip, never the 2nd

rare basin
#

(1,2) can only generate 1

#

(0,4) can generate 0,1,2,3

north kiln
#

!warn 176068058241171456 it's a requirement that newcomers configure their IDE, and we do not want people to answer their questions to avoid time wasting. Your argumentative attitude is unwelcome and unhelpful. If you don't want to follow our rules you are welcome to leave.

eternal falconBOT
#

dynoSuccess smokingheadstudio has been warned.

west sonnet
rare basin
#

as i said, it is exclusive

#

so adapt it to the knowledge

ivory bobcat
# icy grotto hi, can this one be converted to a Ternary operator?

If Statement:cs if (condition) result = first; else result = second;Ternary:cs result = condition ? first : second;Note that ternary requires the first and second results whereas an if statement doesn't necessarily require any results (nothing has to be done in an if statement).

west sonnet
#

I'm not entirely sure what exclusive means. It means it doesn't include the last digit?

rare basin
#

yes

#

it's a range from A to B, where B is exlusive

west sonnet
#

Does you know why it's exclusive?

north kiln
#

So you can simply pass an array length without requiring subtraction

rare basin
#

to align with typical behaviour with arrays i guess

west sonnet
#

Okay, thanks

honest haven
#
            {
   ``` trying to move the raycast up off the ground to detect the playe but it wont move seems to shout ground level only
#

seems to cast at ground level rather then a waist height

barren aurora
rare basin
#

experienced dev can just tell that by looking at code screenshots

#

code not auto completing, different types coloring, no errors highlight

barren aurora
north kiln
#

Also poorly formatted and aligned code

barren aurora
rare basin
#

Delusional 😄

#

Keep programming without your IDE configured

#

have fun

#

When are you "finally" off?

ivory bobcat
barren aurora
rare basin
#

Wait, you are programming for almost 9 YEARS NOW

#

without your IDE configured?

#

the fuck did I just read

#

somebody mute this troll lol

ivory bobcat
#

Not trying to say anything but anyone who brags probably hasn't been coding long enough yet.

rare basin
#

2000 game object scripts, no ide configured and 60fps

barren aurora
# rare basin Wait, you are programming for almost 9 YEARS NOW

Note:
Things must - work -

I don't care what you mean by a "configured IDE". Ergo: I don't read through what garbage is written there if everything works perfectly.

If I encounter a problem, I solve it.
It's like patterns: yes, they can make sense.
But code is code, the result has to work.

As long as your car runs, there's no reason to rewrite everything just because you don't like the way you capitalize variables.

... just think about it.
The result speaks for the work.
Not the form.

ivory bobcat
#

I mean, if you've code from the 80's, 90's or even 2000's you'd know tech comes and go... everyone's always learning.. "pro", what's that?

rare basin
#

so im done talking

#

don't spam the channel with offtopic now

tight saffron
#

can someone help me? my movement jump fall run and idle is okay but when i added a movement climb suddenly my character is moving so slow and not jumping

barren aurora
north kiln
rare basin
#

from your complex project

#

could you send it?

barren aurora
tight saffron
#

can someone help me? my movement jump, fall, run, and idle is okay but when i added a movement climb suddenly my character is moving so slow and not jumping

barren aurora
eternal falconBOT
rare basin
#

@barren aurora is there any chance you could send a sample code from one of your complex projects?

barren aurora