#💻┃code-beginner

1 messages · Page 680 of 1

rocky canyon
#

makes sense, roger 📻

#
void OnAppQuit() {
    isQuitting = true;
}``` ya, such as
naive pawn
#

may as well use a lambda since you wouldn't have to unsubscribe in that scenario

rocky canyon
#
 Application.quitting += () => IsQuitting = true;```
#

💪 (i think) lol

naive pawn
#

yeah i was basically just debating between that and the separate message

rocky canyon
#

i love syntax sugar..

naive pawn
#

i don't remember why i used the message, i don't think there's any practical difference (in this case where it's just for checking exiting playmode)

rocky canyon
#

i try to stay away from things that look good.. but make me second glance.. or think too much

slender nymph
rocky canyon
#

edge-cases!! Ftw

naive pawn
#

ah, i haven't touched on disabling domain reload so i didn't even consider that lol

rocky canyon
#

boxfriends comment was met with "you're already thinking like a pro" 😊

naive pawn
#

i should probably look into the domain reload thing

rocky canyon
#
bool myBool => testBool();```
#

this is about as fancy as i get

naive pawn
#

is domain reload required after a recompile, regardless of that setting?

slender nymph
#

yeah

#

that setting only affects the domain reload for entering play mode

naive pawn
#

gotcha

hollow surge
#

Where I can learn much things to get better in Programming in Unity? I'm looking for very good tutorials becasue I watched a lot of tutorials and 99% of them are about things I already know like: Variables, GameObjects, Colliders, Collision Detections, ScriptableObjects, Tags, AI, etc.

slender nymph
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

hollow surge
#

Is there any clear and good documentation?

#

!documentation

slender nymph
#

!docs

eternal falconBOT
hollow surge
#

Is this tutorial good?

#

I only want learn programming

slender nymph
#

yes, the pathways are a good place to learn how to use the engine

hollow surge
#

I already know how to navigate in Engine

#

I know how to make Animations, Cutscenes, just the everything in interface

hollow surge
brave idol
slender nymph
eternal falconBOT
rocky canyon
#

quick rundown: @brave idol says that his GameManager gets destroyed as soon as he starts the game

#

DontDestroyOnLoad(this); may need to be changed to DontDestroyOnLoad(this.gameObject);

#

i kinda figured the gameobject would also remain if u DDOL the component its attached to.. but just to be certain u could change it real quick

brave idol
#

alright will try that

green copper
#

With this structure, will it be fine going forward if I attach the Rigidbody2D to the Hull component? The hull script will contain the movement type information and code, and I'm not sure if I'll need to make it feel the information to the root, or if it'll be fine to let the Hull object hold the sprite and necessary colliders

#

I think it'll be fine with my current understanding but I don't want to learn that some property of collisions will make everything harder in a few hours or days

slender nymph
#

if the rigidbody is on Hull then only hull will be affected by physics. you need the rigidbody on the root object if you want it all to move as one piece with physics

green copper
#

Understood, thank you!

muted sapphire
#

In a third person 2D birds view RPG, should one make every room its own scene?

#

Or should you instead write some room switcher

frail hawk
muted sapphire
#

Oh wait

#

thats actually much simpler

#

just move the camera

frail hawk
#

yep

muted sapphire
#

also allows for far more freedom

#

means i can make bigger rooms and make the camera track to a certain limit

#

thank you

rocky canyon
#

seems about average of what u'd see while building a controller.

muted sapphire
strong shoal
#

if (_timeLeft > 0 && useAction.IsPressed())
{
_rb.AddForce(0, 1.5f, 0, ForceMode.Acceleration);
_timeLeft -= Time.deltaTime;
_particleSystem.Play();
}
if (!useAction.IsPressed())
{
_particleSystem.Stop();
}

#

can someone tell me why its not working???

polar acorn
#

You're going to have to be more specific about what "not working" means

#

Also, !code

eternal falconBOT
strong shoal
#

private void Update()
{
if (_playerScript.IsGrounded && _timeLeft <= 2.5f)
{
_timeLeft += Time.deltaTime * 2;
}

    if (_timeLeft > 0 && useAction.IsPressed())
    {
        _rb.AddForce(0, 1.5f, 0, ForceMode.Acceleration);
        _timeLeft -= Time.deltaTime;
        _particleSystem.Play();
    }
    if (!useAction.IsPressed())
    {
        _particleSystem.Stop();
    }
}
polar acorn
wintry quarry
#

that will reset it

#

every frame

strong shoal
polar acorn
wintry quarry
strong shoal
wintry quarry
#

there are many ways to write incorrect code. I wouldn't be surprised if you found two of them

polar acorn
strong shoal
wintry quarry
strong shoal
# polar acorn How did you actually do it in that case

private void Update()
{
if (_playerScript.IsGrounded && _timeLeft <= 2.5f)
{
_timeLeft += Time.deltaTime * 2;
}

    if (_timeLeft > 0 && useAction.IsPressed())
    {
        _rb.AddForce(0, 1.5f, 0, ForceMode.Acceleration);
        _timeLeft -= Time.deltaTime;
        if (!_particleSystem.isPlaying)
        {
            _particleSystem.Play();
        }
    }
    if (!useAction.IsPressed() && _particleSystem.isPlaying)
    {
        _particleSystem.Stop();
    }
}
#

thats how i did it

wintry quarry
#

Start using Debug.Log

#

and make sure thre's no errors in console too

polar acorn
eternal falconBOT
strong shoal
strong shoal
#

before

polar acorn
green copper
#

why would the presence of a boxcollider2d on an object affect the amount addTorque has on it?

I fixed my bug where one nearly identical vehicle had a completely different turn rate, but I have zero idea why that would be the case

strong shoal
#

wait so its a problem with the particles

green copper
polar acorn
# strong shoal that it is

If it's logging "Play" when you expect it to, and it's logging "Stop" when you expect it to, then the code is working

wintry quarry
#

Like real objects

#

And the colliders define the shape

green copper
#

Ohhhh so the one with a collider had more inertia, which meant the drag force affected it less

strong shoal
#

OHHHH IM STUPID ASS HELL

#

the position of the particles was above the player

#

im sry for wasting ur time

#

thx for help

wintry quarry
simple hawk
#

I made this script for my enemy to deal dmg to my player's health, but the health variable isn't decreasing

polar acorn
naive pawn
#

and is damage set

simple hawk
simple hawk
late badger
cosmic dagger
late badger
#

Like did u put the script into that slot

polar acorn
#

What did it print

simple hawk
simple hawk
polar acorn
naive pawn
simple hawk
simple hawk
naive pawn
# simple hawk

you were supposed to print the variable, not as a string

naive pawn
#

drag the actual player into the slot

#

or is this a prefab where you can't do that?

polar acorn
simple hawk
polar acorn
#

not a string

simple hawk
simple hawk
naive pawn
#

are you instantiating the enemy at runtime?

simple hawk
naive pawn
#

so it is going down - the issue is that it's a different counter than the one you're expecting, since you assigned the prefab

polar acorn
# simple hawk

Yes, we've established now that you're changing the CurrentHealth of the prefab

simple hawk
#

ohhh, I see

naive pawn
simple hawk
#

I think? this is the code I used for it

indigo notch
#

instantiating means to create a copy of a gameObject right?

polar acorn
naive pawn
polar acorn
#

Better idea: If this thing collides with the player, why not just get the Health component of the thing you hit

rich adder
naive pawn
#

you're starting a coroutine every frame, and thus it will always be spawning
just use a single coroutine from Start or something and do a loop

simple hawk
polar acorn
# simple hawk I am extremely noob at coding, I'm planning to actually learn (from the start) w...
simple hawk
#

thnx

simple hawk
polar acorn
late badger
simple hawk
#

wait, I might be stupid, could this be why the code isn't working?

naive pawn
#

what do you mean by "this" exactly

simple hawk
#

should've highlighted, I'm referring to the part at the bottom

naive pawn
#

you aren't even setting currentHealth here

simple hawk
#

could that be it?

polar acorn
naive pawn
# simple hawk

according to your above code, you're using a trigger
that message won't even run - as evidenced by the lack of a log

ivory bobcat
ashen arch
#

public int currentHealth = 3;

simple hawk
naive pawn
naive pawn
polar acorn
#

This object has a function that runs when this object collides with a solid object. The other script you showed has a function that runs when that object collides with a non-solid object

ivory bobcat
# simple hawk should've highlighted, I'm referring to the part at the bottom

If you aren't getting any messages in the console it could be due to a variety of things. First off, is a collision really happening? Are the two objects pushing each other etc. Second, does the other object have the tag "zombie" (case sensitive)? Third, well this should've been first but I'm too busy/lazy to edit this, are you certain this is a 2d environment or 3d (both use their own physics system)?

simple hawk
#

ok, I might be incredibly stupid if this is the case: but, since the enemy's dmg script damages the prefab's health variable.. could the problem be that the prefab doesn't have a 2D collider?

polar acorn
naive pawn
ivory bobcat
simple hawk
#

I managed to fix it by making the player's collider not a trigger, not sure what that did exactly, but now it can't attack

naive pawn
#

are you on a 5 minute deadline or something

polar acorn
naive pawn
#

you should probably step back and do a proper unity tutorial instead of guessing and checking everything

simple hawk
naive pawn
#

do it in the other order

#

it'll be much easier

simple hawk
#

yea, ur probs right, I'm going to leave it here, set up the itch page and focus on tutorials

#

thnx for the help guys, and sorry for the trouble

naive pawn
#

you don't have to put it entirely down

orchid swallow
#

Hi , how to fix rb.velocity //(-velocity-) is dashed out and only have linearlyvelocity and angularvelocity for 2D

naive pawn
#

just- figure out what you're doing instead of doing random stuff until it works

naive pawn
simple hawk
orchid swallow
polar acorn
#

yes

slender nymph
#

it's the same thing, just a rename to make it clearer what it is for

orchid swallow
#

Thanks

orchid swallow
#

why the inerted sprite went missing when play?

polar acorn
orchid swallow
polar acorn
orchid swallow
pearl current
#

Hey guys, this is my first time making a top down 2d roguelike and i'm running into a rotation issue with my polygon collider.

From these 2 images you can see that it starts out positioned right in front of the character, but after moving in a direction, my calculation is supposed to rotate the z value according to the users last input. However, when i rotate the parent objects z value to say 90 degrees, it throws my collider far away from my character. Does anyone know how I might be able to fix this to have it stay right in front of the character after rotating?

Here's the code snippet that makes the calculation as well:

{
    Vector2 moveDirection = Vector2.zero;

    if (Input.GetKey(KeyCode.W)) moveDirection.y += 1;
    if (Input.GetKey(KeyCode.S)) moveDirection.y -= 1;
    if (Input.GetKey(KeyCode.D)) moveDirection.x += 1;
    if (Input.GetKey(KeyCode.A)) moveDirection.x -= 1;

    if (moveDirection != Vector2.zero)
    {
        moveDirection.Normalize();
        transform.Translate(moveDirection * moveSpeed * Time.deltaTime);
        animator.SetBool("isMoving", true);
        lastMoveDirection = moveDirection;

        Vector3 aim = Vector3.left * lastMoveDirection.x + Vector3.down * lastMoveDirection.y;
        Aim.rotation = Quaternion.LookRotation(Vector3.forward, aim);
    }
    else
    {
        animator.SetBool("isMoving", false);
    }
}```
plain raptor
#

Im getting an error that says "Can't add script behaviour 'Player'. The script needs to derive from MonoBehaviour!" but the internet says this script should work; whats wrong with it?

using UnityEngine;

public class Player : MonoBehaviour
{
private Vector3 direction

public float gravity = -9.8f;

}

sour fulcrum
#

where is that error being said

plain raptor
sour fulcrum
#

is that script saved

plain raptor
#

I rarely use my pc so I might just be an idiot tho

rich adder
#

actually nvm

#

your script didn't save/compile cause you have compile errors

#

ermm ```cs
private Vector3 direction

public float gravity = -9.8f;```
#

look at console window you most likely have the error there since your IDE might not be configured

acoustic belfry
#

hey, in a 2d plataform space how i can make a npc detect my player pos but with "lag". I mean, for now my rifle enemies know where the player pos is and shoot at it, very good. But now for the bosses and such, maybe a railcannon, i want it to know where the player was once, not where it is right now, so the player can dodge it

#

this is how i can detect the player

 {
     distancia = objetivo.position.x - transform.position.x;
     distanciaAbsoluta = Mathf.Abs(distancia);
 }```
this is how i can shoot at it
```protected void dispararBalas(GameObject balas, Transform balasPos, float firingspeed, float bulletspeed, float angulo)
{
        GameObject nuevoProyectil = Instantiate(balas, balasPos.position, Quaternion.identity);
        Vector3 direccion = (objetivo.position - balasPos.position).normalized;
        Rigidbody2D rb = nuevoProyectil.GetComponent<Rigidbody2D>();
        Vector3 direccionAngulo = Quaternion.Euler(0, 0, angulo) * direccion;
        if (rb != null)
        {
            rb.linearVelocity = direccionAngulo * bulletspeed;
        }
}```
rich adder
acoustic belfry
rich adder
#

use a variable

acoustic belfry
#

ahh, you mean that

#

idk i thought store was another thing

#

you mean putting the player pos inside a value

#

and use that value

rich adder
#

yes thats one way to store info for later usage

acoustic belfry
#

oooooooh ofc, in a non-updating way

rich adder
#

how often you update is. up to you

acoustic belfry
#

so it only has what it readed that time

#

thanks :3

rich adder
#

also can be done based on distance moved by player etc

pearl current
#

hey nav, how good are you with rotating colliders...

rich adder
rich adder
pearl current
#

1 sec

rich adder
#

screenshot again after

pearl current
#

kks

#

this is for the aim object:

rich adder
#

what about Aim ?

#

ok yea thats wayyy off lol

pearl current
#

wtf

#

how'd it even do that???

rich adder
#

Center mode strikes again

#

because when you use Center mode you're not seeing the true origin point so you may be further than shown when you moved it around

pearl current
#

so how do i go about aligning the 2 objects?

#

move melee to aim?

rich adder
#

just reset the transform on AIm

#

and adjust from there

#

might need to reset pos the melee thing too.
btw shouldn't that be a trigger?

pearl current
#

you're probably right, and yes it should be but for early testing purposes i left it on to make sure it was there

rich adder
pearl current
#

you're right there again... i just didn't implement it in the code...

rich adder
#

the code might be okay, its always best to fix these gizmos / pivots first to make sure the rotation will be accurate

pearl current
#

you're a LIFESAVER! i adjusted the 2 objects and now it works perfectly

#

tysm i was stuck all day <3

rich adder
pearl current
#

also should i stick to developing in pivot mode?

#

i'm new to game development with a coding background and want to know best practices going forward

rich adder
#

yeah I rarely find use in Center mode unless you're rotating a group of objects together around a point in Scene view

#

Kinda weird for unity putting that as default as it messes people up a lot if you're not aware of it in the beginning, esp in code where transform.position doesnt match for example

pearl current
#

DUDE IK

#

i was bug fixing all day

#

and this shit didn't make aaaany sense to me

#

bashing my head into a wall

rich adder
#

haha yeah it used to trip me up to in the beginning for position

pearl current
#

do you have any sources that has more of these useful tips for new developers other than youtube or stack overflow?

rich adder
eternal falconBOT
rich adder
#

some favorite channels that had good content were official Unity channel, Jason Weiman, LLamma academy
and some stuff on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

pearl current
#

noted! tysm

past yarrow
#

(Once I click on a mine, I want to reveal where all the mines were before restarting the game 5 sec later.)

eternal needle
wintry quarry
sharp bloom
#

Oh shit, I finally got this kind of bug

#

The 32-bit maximum value XD

umbral bough
#

Hi, I am trying to use the localization package and can't figure out how to listen for changes from a function.
I got this:

private void HandleNameTMPChanged()
{
    if (_nameLocalizeStringEvent)
        _nameLocalizeStringEvent.OnUpdateString.RemoveListener(UpdateNameText);
    _nameLocalizeStringEvent =
        _nameTMP?.gameObject.GetOrAddComponent<LocalizeStringEvent>();
    if (_nameLocalizeStringEvent)
        _nameLocalizeStringEvent.OnUpdateString.AddListener(UpdateNameText);

    Debug.Log(_nameLocalizeStringEvent);
}

And Debug.Log shows that it's not null, however, I don't see my method added in the inspector nor does it execute.
What is going on?

sour fulcrum
#

just a heads up that you shouldn't use ? to null check unity objects, it has inconsistent results due to reasons

umbral bough
#

Ok, my bad, I think that the event listener is added but I don't know how to trigger the change when I edit the component like this:

_nameLocalizeStringEvent.StringReference = ItemManager.SelectedItem?.LocalizedString;
_nameLocalizeStringEvent.RefreshString();

This sometimes works, it's very inconsistent tho.

eternal needle
umbral bough
#

They appear to be using the .RefreshString method, that's what I am doing aswell, am I missing something?

#

I added this Debug.Log() right above the refresh and I can see it being called, however, the name just doesn't update:
Debug.Log(_nameLocalizeStringEvent.StringReference);

#

I am honestly beyond confused :/

umbral bough
#

if anyone is able to help, please @ me, thanks in advance!

#

ok, I genuinely have 0 clue what happened but it seems to be fixed out of nowhere, I literally just walked away from my pc and it's working now 😭

#

and it's not working again, I just give up at this point, again, if someone could happen to have a clue as to what's going on please @ me, I would highly appreciate it :/

#

Last message, I hope, I think I figured it out.
You gotta do it like this:

_nameLocalizeStringEvent.StringReference
                        .SetReference(ls.TableReference, ls.TableEntryReference);
ls.RefreshString();
_nameLocalizeStringEvent.RefreshString();

You can't use _nameLocalizeStringEvent.StringReference = ls; instead of SetReference.
This is so odd, especially considering the fact the setter for StringReference is public, but whatever.
Hopefully it stays at this and I never encounter this issue again...

unique quartz
#

I'm making these rabbits move by themselves with simple ai, but their idle animations dive into this, then dive back up to normal when they run. Disabling root motion stopped them from diving down, but it altered their movement and made them slow

#

i will also add they float in game mode but don't in scene mode

rocky turtle
#

Can someone teach me c# in unity?

sour fulcrum
unique quartz
burnt vapor
#

I highly suggest you learn C# basics before touching Unity in any way.

pulsar helm
burnt vapor
#

It really depends on your experience but the majority of people getting into C# and Unity have no prior experience with programming. You really shoot yourself in the foot by combining them, especially given Unity's horrible implementation of C#

#

Especially since they ask for both C# basics and Unity, you really should get used to the syntax first. That's also why the pinned post has the Intro to C# link

#

Long term it's faster and less frustrating than taking them both at the same time

pulsar helm
#

Oh okay, yeah if there is absolutely no prior programming experience maybe it's questionnable as you say

#

I still believe that if you have a correct approach, you may begin with Unity to learn C#, I think you can to pretty simple things with it, like if you have an input, you just move a transform, or even play with forces with rigidbodies pretty intuitively (well at first not really, but you learn fast).

sour fulcrum
#

I'm kind of suprised the pin doesn't include any interactive beginner tutorials

#

the microsoft beginner guide is super extensive but it's quite offputting for a complete beginner imo

pulsar helm
#

Also I'm curious, @burnt vapor why do you think Unity implements the C# language horribly?

sour fulcrum
#

i'd also be curious if the answer contains alternative solutions

burnt vapor
#

Bugs with constructors in Unity, bugs with any type of null-coalescing or null-conditional operators that work in an unintended way on game objects in comparison to comparing to null directly

charred spoke
#

I wish unity just expose a way to use c++

#

Then we won’t have to jump interop hoops

burnt vapor
#

It's years and years of bad ideas and the fact they supported UnityScript or whatever it was called which just made it worse

sour fulcrum
#

i don't think those two make it a "horrible" implementation

burnt vapor
#

I don't solve it, Unity should have made it work from the start

sour fulcrum
#

how

#

what is the proposed behaviour

burnt vapor
#

You don't find it horrible that a very normal C# implementation doesn't work in Unity?

pulsar helm
#

Fair point for the null-related thing, but at the same time, i understand the design

burnt vapor
#

Do you know what issue constructors have in Unity?

sour fulcrum
#

I know MonoBehaviours are designed to completely avoid them because of there fundemental design

burnt vapor
sour fulcrum
#

wont a majority of checks be (if object == null || object.IsDestroyed) then

burnt vapor
pulsar helm
#

I guess it's a way to reduce verbosity? But I get that it's not really great because this object itself is not null and can hide the real memory management

pulsar helm
burnt vapor
#

Overriding null is horrible, you don't expect it to check if something is destroyed. You expect the reference to be gone

sour fulcrum
#

for 90% of people they do not care about that difference and the other 10% are nerds who know whats going on entirely

#

whats wrong with constructors

pulsar helm
#

You must use the Instantiate function instead, maybe this is because some requirement about unity can't fit in the constructor in some way? I don't have the knowledge for this

burnt vapor
sour fulcrum
#

Would you prefer another function getting run immediately on creation regardless of active state?

#

to be honest it would feel a little weird of monobehaviour constructors worked period

burnt vapor
#

Why would this be weird?

pulsar helm
#

I think that in the end, they made this design choice (null overriding) because of clarity.
Imagine having object?.IsDestroyed called to check if the object exists: it makes perfect sense alright, but it can be tricky for beginners to understand that it's not about a object being destroyed, but its mere existence at all.

So I understand why they chose to keep it "simple" by just having object == null which is more likely to be understand as "we have a valid object" than object?.IsDestroyed

sour fulcrum
#

Curious what a preferable solution would be using c# constructors and enforcing the design descision that all monobehaviours must exist in the context of a gameobject

pulsar helm
nimble apex
#

i want to enable preview features in my project so i can use some functions that i cant use before

#

which file should i modify?

teal viper
#

What kind of preview features? And what makes you think that modifying the cs project is gonna help with that?

nimble apex
#

in C#14 theres a new features called extension method?

#

but it needs to "enable preview features"

#

and when i google how to enable it, i saw some article saying modify the csproj helps, maybe i will look into it more lol

teal viper
#

Unity only supports C# 9 according to the docs.
And csproj are only used for intellisense. Modifying these files might help in the ide, but the code wouldn't compile anyway.

nimble apex
#

ty 👍

runic lance
#

extension methods are supported just fine though

pulsar helm
# nimble apex in C#14 theres a new features called extension method?

Are you talking about making a static method with an argument, but the first argument can be considered as the object to call the function on?
like :

// In some .cs file
static class ExtensionThing
{
  public static void DoSomething(this YourObjectType yourObject)
  {
    // Do something with yourObject
  }
}

// Somewhere in your project
// ..
  YourObjectType instanceOfObject = new();
  instanceOfObject.DoSomething(); // Allowed because the ExtensionThing class is STATIC, and the function has the first parameter marked as "THIS".
  ExtensionThing.DoSomething(instanceOfObject); // Also allowed, since it's the default behaviour
// ..
#

in that case, it is supported

teal viper
#

Ah, extension methods are not C# 14 though

pulsar helm
#

More on this article, a certain syntax is indeed only for C#14, but you don't really need it.

nimble apex
#

that "extension" is a new thing right?

pulsar helm
#

Yes this syntax is only for C#14 or newer

#

but you can basically do the same with the "old" syntax, which is what I send as code above

nimble apex
#

nice i gonna try it , ty 👍

burnt vapor
# nimble apex

AFAIK Unity overwrites anything done in the csproj so the answer is that you can't

#

You might be able to add a Directory.Build.props file to your project and place it in there. It will take effect over all csproj files and Unity won't modify it

#

Considering how ancient Unity's langversion is it would still be nice to have if you can at least bump it to 13

vocal wharf
#

So I made a spherical planet and I want my player to walk on the planet while staying aligned and always upright relative to the center of the sphere. I already made simple gravity using rb.AddForce() but I still need a way to always have the player perpendicular to the sphere's surface. I looked on youtube but the only tutorial I found basically just told me to download his code and didn't show how it worked. Any help is appreciated!

#

the gravity script is on the planet and it references the player rigidbody. In case that matters
edit: here's the gravity script since it might be helpful

public class Gravity : MonoBehaviour
{
    public Rigidbody[] rigidBodies;
    public GameObject planet;
    private Vector3 gravityDirection;
    public float gravityStrength = 1f;
    void FixedUpdate()
    {
        foreach (Rigidbody rb in rigidBodies)
        {
            gravityDirection = rb.transform.position - planet.transform.position;
            rb.AddForce(gravityDirection * -gravityStrength);
        }
        
    }
}
ruby python
#

Hi all,

So, I'm having a weird raycast issue and can't seem to see what's going wrong.

I'm generating a world in a tile pattern and need to add a spawn point to each 'chunk'. Everything is working, but the raycast I have on the spawnPoint object is 'missing' the terrain collider (It's hits it, but the hit.point y axis is very wrong, it's way lower than it should be). My layer mask etc. is all correctly assigned, and the terrain collider does work because I can walk around on the islands (manually moving of the character to test)

So, I'm a little bit baffled.

The debug is spitting out a hit.point position as 0, 3.27f, 0, which given the hit point is actually around 200 is confusing.

Here is the full script.....

https://hastebin.com/share/ifomumatah.csharp

and here's just the SpawnPointGeneration part.

GameObject newSpawnPoint = new GameObject();
newSpawnPoint.name = newIsland.name + " Spawn Point";
newSpawnPoint.transform.parent = newIsland.transform;
newSpawnPoint.transform.localPosition = new Vector3(0, 500, 0);

RaycastHit hit;
Vector3 raycastOrigin = new Vector3(newSpawnPoint.transform.position.x, newSpawnPoint.transform.position.y, newSpawnPoint.transform.position.z);
if (Physics.Raycast(raycastOrigin, newSpawnPoint.transform.TransformDirection(Vector3.down), out hit, Mathf.Infinity, layerMask))
{
    Debug.Log("Hit Ground @ "+hit.point);
    newSpawnPoint.transform.position = new Vector3(hit.point.x+0.5f, hit.point.y+1, hit.point.z+0.5f);
}
else
{
    Debug.Log("Did Not hit Ground");
}
dataManager.spawnPoints.Add(newSpawnPoint);

Anybody see or have any ideas as to what's happening? Cause I just can't see it 😕

nimble apex
burnt vapor
#

Try the props file I mentioned

nimble apex
burnt vapor
#

Huh

#

I assume it just works out of the box, unless Unity doesn't allow for this

nimble apex
#

if that plugin is not necessary i can try it again👍

#

when i google it , the article said i should install csprojmodifier and import .props files from there

#

but if u install that plugin , it will have conflict with unuty.test-runner , i havent used that so idk what that is

faint agate
#

Hey guys, so I have a script that tells me when a button is selected or deselected. Let me say I'm using keyboard navigation so keep that in mind. I also have a system where if the player doesn't meet the KhronsAmount, the button will be locked(thisButton.interactable = false;).

My problem is that when I'm CURRENTLY on the button and want to lock the button so the player cant press it, the keyboard navigation stops working. I checked and its deselecting the button but somehow its still selected.

If I lock the button while on another button, its fine. I want to also be able to lock it when currently on it.
https://pastecode.io/s/rn7shapg

eternal needle
past yarrow
#

is it because I didn't clear the Coroutine first before creating a new one ?

naive pawn
#

you have infinite recursion between OnTileClicked, OnGameOver, and RevealTile

eternal needle
polar acorn
naive pawn
#

when you click on a mine, you game over.
when you game over, you click on all tiles, meaning you click on a mine

eternal needle
#

actually i got the order wrong since OnGameOver is the one calling RevealTile as well, which invokes the event too

#

so this is like double infinite recursion

past yarrow
#

So do I remove the event invoking in "RevealTile()" ?

eternal needle
#

maybe that means RevealTile shouldnt invoke the action. Maybe GameManagers OnTileClicked shouldnt reveal a tile under certain scenarios

#

the only thing I notice here is that you seemingly have this visitedNeighbours hashset which you dont use, and a tile.Visited property that never is set.
maybe you forgot to finish writing the logic for not infinitely checking over neighbour tiles. Maybe ai hallucinated if you used ai here

nimble apex
# burnt vapor Huh

just curious when u do the "directory.build.prop" file u havent installed any of the plugins? just place it directly to rootpath?

split plover
#

Dumb question but do i have to rename a class in my script if i rename the script

#

also unrelated but should i update visual studio whenever it gives me the option to update?

polar acorn
#

As long as there's only one class in the file

split plover
#

Well good thing im using unity 6 i guess cause im probably going to be renaming scripts a lot

still ingot
#

Hi I am trying to check when my cutscene video ends. I tried using a simple example code and find myself running into an error with the CheckOver function I made, and the loopPointReached? Any suggestions as to what could be wrong?

using UnityEngine;
using UnityEngine.Video;

public class VideoPlayer : MonoBehaviour
{
    [SerializeField]
    VideoPlayer video;

    void Start() { 
        video.loopPointReached += CheckOver; 
    }

    void CheckOver(VideoPlayer vp)
    {
        print("Video Is Over");
    }
}
split plover
#

you have to put it in update

#

start only happens when the script is made if im correct, update happens every frame

#

idk if thats the only issue but thats the only thing that i would personally know

solar arch
#

i have a custom class that i want to assign to GameObjects in the inspector (using a [SerializeField]). I'm assuming this is possible i just don't know how to actually put the data in. My custom class has the tag [System.Serializable], so i just need to work out how to put the data into here -- "Price" should take my custom class. If you need more info please ask

nimble apex
#

at the end i gonna make my own extension method like this

eternal needle
split plover
#

but wait how would it work if its in start and not update

#

atleast from what i know that code would never work unless its in update

eternal needle
vocal wharf
eternal needle
split plover
#

ok

polar acorn
#

because every frame it'd add another copy of the function to that event

split plover
#

😭

polar acorn
# still ingot

Your issue is that this class is named VideoPlayer. And it doesn't have any events named loopPointReached

polar acorn
split plover
#

i was trying to read on it but you pinged me

eternal needle
polar acorn
#

They're using this one

eternal needle
vocal wharf
eternal needle
#

Its the same thing still, the player needs to just know what direction down is

#

They can calculate that by having a reference to the planet they're on

split plover
#

okay ik this is dumb but google doesn't understand my question, does < check if something is under the second value or above the second value

vocal wharf
modest dust
eternal needle
split plover
ruby python
split plover
#

thank you 😭

vocal wharf
eternal needle
# vocal wharf which part?

the only part there where you multiply two quaternions. i think it should be
rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector)

polar acorn
split plover
ruby python
vocal wharf
pulsar helm
eternal needle
vocal wharf
#

oh interesting

vocal wharf
# eternal needle the only part there where you multiply two quaternions. i think it should be `r...

I fixed that part but my player still spins extremely fast as soon as I press play. This is the only active script in the scene. Any idea what could be wrong?

public class Gravity : MonoBehaviour
{
    public Rigidbody[] rigidBodies;
    public GameObject planet;
    private Vector3 gravityVector;
    private Vector3 rigidBodyVector;
    public float gravityStrength = 1f;
    void FixedUpdate()
    {
        foreach (Rigidbody rb in rigidBodies)
        {
            gravityVector = (rb.transform.position - planet.transform.position).normalized;
            rigidBodyVector = (rb.transform.eulerAngles).normalized;
            rb.AddForce(gravityVector * -gravityStrength);
            Quaternion targetRotation = rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector);
            rb.rotation = Quaternion.Slerp(rb.rotation, targetRotation, 100);
        }
        
    }
}
polar acorn
vocal wharf
#

hmm ok

eternal needle
#

thats definitely interesting if that was directly from a Sebastian Lague video, i have doubts about that being the final code he wrote.
though maybe you also want to do this logic on the player directly? otherwise everything with a rb is going to try and align itself like this

vocal wharf
#

I tried 0.5 but it gives the same result

eternal needle
#

because you're not using Slerp as it should be used, you cant just plug in random values

vocal wharf
#

keep in mind this was an 11 year old tutorial

polar acorn
#

50 has never been a valid third parameter for slerp

vocal wharf
#

he shows the Quaternion.Slerp part at 10:28

runic lance
#

he's multiplying by Time.deltaTime, which is usually a very small value

vocal wharf
#

ah

#

I had everything in FixedUpdate so I figured I shouldn't put that

rich adder
polar acorn
#
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 189
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-06-19
vocal wharf
#

lemme switch to the Update method and see what happens

eternal needle
#

you dont need to swap to Update though

rich adder
polar acorn
#

It still isn't the best way to do this, in a more modern tutorial he'd be using RotateTowards

vocal wharf
#

and it still spins lol

polar acorn
#

But Slerp's third parameter is a percentile value for how much of the way between the first two parameters you want. 0 means first parameter. 1 means second. 0.5 means halfway between the two

vocal wharf
#

looks like I need to go back to the drawing board notlikethis

past yarrow
# eternal needle thats for you to decide on how to fix this. im looking at this error purely from...

Problem solved 🤔 Thanks 🙏

  • I don't have the stack overflow anymore and all the mines reveal correctly but right now I have this error that appeared once (the second try it didn't appear, third try it appears again when I clicked on a mine)
  • also my game revealing neighbors that are 0 and their surroundings don't work anymore as you can see with those empty revealed tiles 🤔
    https://paste.mod.gg/lqldofmnpdos/0
polar acorn
vocal wharf
# polar acorn It _still_ isn't the best way to do this, in a more modern tutorial he'd be usin...

I tried to redo it with RotateTowards just by memory from other projects but I must be overlooking something simple because my player still spins in place and changing the max angle in the RotateTowards argument just changes how fast it spins. I'm very sorry but I can't think of what could be wrong.

foreach (Rigidbody rb in rigidBodies)
{
    gravityVector = (rb.transform.position - planet.transform.position).normalized;
    rigidBodyVector = (rb.transform.eulerAngles).normalized;
    rb.AddForce(gravityVector * -gravityStrength);
    Quaternion currentRotation = rb.transform.rotation;
    Quaternion targetRotation = rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector);
    rb.rotation = Quaternion.RotateTowards(currentRotation, targetRotation, 1);
}
polar acorn
vocal wharf
#

sorry nvm

polar acorn
#

So that sounds like a problem. gravityVector is obviously supposed to be pointing in the direction of gravity, but what's rigidBodyVector supposed to represent?

vocal wharf
#

accidently put rigidbodyvector as both rays 🤦‍♂️

#

my apologies

#

ok the gravityvector ray is constantly pointing at the center of the planet which is good

vocal wharf
#

all to get the player to always face feet down on the sphere

polar acorn
#

Those aren't the same thing

vocal wharf
#

lol uh that's not good I didn't notice

polar acorn
#

Consider an object with euler angles of 0, 180, 0, that's going to be facing backwards, but the normalized value of that is 0, 1, 0 which is straight up

#

If you want the direction the object is facing, use transform.forward

sharp bloom
#
        var listEvents = events.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
        foreach (var x in listEvents)
        {
            Debug.Log(x.FieldType.ToString());
            if (x.FieldType == typeof(System.Action))
            {
                GameEvents.TryAdd(x.Name, (System.Action)x.GetValue(x));
            }

Why does this array come up empty? If put something like string instead of System.Action, it does find them

vocal wharf
vocal wharf
#

oh it's already normalized got it

polar acorn
sharp bloom
#

Ye but it does though

polar acorn
#

What do the logs say?

sharp bloom
#

Just this with my current code

#

To verify it even runs

rich adder
vocal wharf
#

Now the player vector is pointing out the front of the body (it's a cube) but the whole player character is still spazzing out

polar acorn
sharp bloom
#

Oh nevermind I'm supposed to use GetEvents() instead of GetFields()

polar acorn
#

You're printing the type of every field

sharp bloom
#

I don't know what I'm even doing here, just messing around

vocal wharf
naive pawn
still ingot
polar acorn
#

Go back to what you had before, then read my other reply to you

#

Your video variable, what thing are you trying to reference with that? What object?

split plover
#

and he's smarter so

#

yeah

quick monolith
#

I made transition between three animation. The problem is character stucks at jumping anim when transition goes from run to jump. Whenever, I stop instead switch to idle staying on jump anim.

#

its a bit complicated

naive pawn
vocal wharf
#

here is the current code again:

foreach (Rigidbody rb in rigidBodies)
{
    gravityVector = (rb.transform.position - planet.transform.position).normalized;
    rigidBodyVector = rb.transform.up;
    Debug.DrawRay(rb.transform.position, gravityVector, Color.green);
    Debug.DrawRay(rb.transform.position, rigidBodyVector, Color.red);
    rb.AddForce(gravityVector * -gravityStrength);
    Quaternion currentRotation = rb.transform.rotation;
    Quaternion targetRotation = rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector);
    rb.transform.rotation = Quaternion.RotateTowards(currentRotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
}
#

rotationSpeed is currently set to 5

mossy jasper
rich adder
#

2025 people using their phones to record a computer monitor instead of video screen capture sadge

mossy jasper
#

And my mic is kinda trash

rich adder
#

what does mic have anything to do with screen recording a video lol

rich adder
#

also pressing 1 Key in OBS is hardly any more work than hitting recording on a phone lol strange times

#

I think microsoft even has their own crap with WinKey + G to record

frail hawk
#

yes

#

game bar

mossy jasper
#

how do i get in bro

frail hawk
#

well as the error says

rich adder
#

man windows is weird as hell

#

what does that even mean

frail hawk
#

save your project somewhere else, dont use system folders

rich adder
#

Windows is case sensitive ?

mossy jasper
#

ok

frail hawk
#

yeah i see that error for the first time

mossy jasper
#

but fr tho, windows weird as hell

slender nymph
rich adder
#

ahh that makes sense

slender nymph
#

it can also be set per-directory so they probably just need to make the project somewhere else, likely where ever the rest of their projects are would work

naive pawn
#

isn't it based on the file system, rather than the operating system

vocal wharf
frail hawk
#

i remember i made something similar to what you have but i am not sure if it was this method i used, been a very long time

vocal wharf
#

I read the doc already but I have no idea what could be wrong

rocky canyon
rich adder
void shell
#

Ladies and gentlemen what the heck

#

I just created the project and it gave me an error

slender nymph
void shell
#

this is a new project, almost blank. i just created 2 sprites

#

i'm running unity hub in arch linux

#

everytime i click to run, i get that "errors need to be fixed before compiling" message, but there's nothing on the console, absolutely nothing

rocky canyon
#

yea, thats b/c the console wont work.. b/c the game wont even go into playmode

#

u have to fix "compile" errors before you'll get runtime errors

rocky canyon
void shell
#

there's only a default scene and a input map, nothing else

rocky canyon
#

if its a completely empty project i'd try to make a new one..

#

u shoudnt have compile errors in an empty project 🤔

#

try a different template maybe

void shell
#

it's the BIRP 2D default in unity 6 LTS, btw

slender nymph
#

it might have something to do with the fact you're running it on an unsupported distro, who knows what could possibly have gone wrong during installation

void shell
#

guess it can be that too

#

i have already used unity on this distro before without errors, it should be something with the version or smt

#

anyway, i'm gonna try to create a new project and see what happens

rocky canyon
#

ya i thinking its installation / ur pc setup and not an actual unity problem

rich adder
void shell
rich adder
#

could be a mix of not official supported distro + newer version not ported properly for linux in general

rocky canyon
#

true true..

void shell
#

damn, it's taking a life to create a new projectr

#

need to get an ssd asap

rocky canyon
#

it'll help marginally.. new projects just take a while

rich adder
#

mechanical are only good for long time storage

rocky canyon
#

after the first start-up sequential ones will be much quicker

void shell
rocky canyon
#

💪 u can never have too many HDDs

#

HDDs are more reliable imo than SSDs

rich adder
rocky canyon
#

ive had more SSDs die on me than i can count

rich adder
#

I have a HDD 5400 rpms that still runs GTA5 lol

void shell
void shell
rocky canyon
#

haha 500 gig is "warm-up"

rich adder
rich adder
void shell
rocky canyon
#

ohhh nooo.. my heavy drive is getting on up there

void shell
#

i have windows 11 + arch linux dual booted on my PC, but while arch takes 2min to boot, windows takes like 15

void shell
rocky canyon
#

gotta have that space 🤪

#

asset hoarder <--

void shell
#

what are you trynna store? the sins of the humankind? damn

rocky canyon
#

just unity projects bro 😄

rich adder
#

they just need a bigger marketshare so these dam big techs would actually shift priority

void shell
#

i got a game i'm making on godot but recently i wanted to do it multiplayer, so i'm getting it into unity, (godot's multiplayer didnt cooked enough)

#

i have 3 years xp on unity but after some trauma i quitted game dev and i'm getting back rn

#

i feel dumb because i forgot too much stuff about C# 😄

rich adder
#

ehh its normal to forget if you don't do it daily or close to that

rocky canyon
#

thats why theres google, unity docs, and stackoverflow 😉

rich adder
#

ya a quick lookup it comes back anyway, its usually not totally forgotten

rocky canyon
#

if u cant find ur solution by using those 3.. it probably isn't possible..
we'll have to learn more about physics first

rich adder
#

the microsoft docs for c# is pretty decent

rocky canyon
#

is it more common to have a scene-manager its own component?
or have the game-manager be in charge of that as well?

#

im torn 🪚

rich adder
#

I got managers everywhere so I prefer the former

rocky canyon
#

just lives alongside the gamemanager?

#

which i assume is like in control of the game-state

rich adder
#

yeah my game manager manages the other managers typically they react with events

rocky canyon
#

ahh fudge!! brb pc is crashing out

rich adder
#

I basically use this pattern I guess
https://refactoring.guru/design-patterns/mediator

void shell
rocky canyon
void shell
#

good luck

rich adder
rocky canyon
#

ya, i figured 16gig would be way enough

rich adder
#

oh 16gb..damm

rocky canyon
#

ive only got 3 projects open

void shell
#

bro wtf

rocky canyon
#

but thats actually a smaller number than ususally so yea something is leaking

void shell
#

WHAT

rich adder
#

running 3 unitys now is more hefty then 3 2019/2020 unitys

void shell
#

bro's trying to fry an egg on the CPU

rich adder
void shell
#

meh, i'm not gonna complain, i got an i3-3240, a RX550 and 12gb ram DDR3

#

the most expensive thing in my setup is my 180hz monitor i guess

#

don't even know how unity runs on that potato

rich adder
#

i've seen worse to be considered a potato

#

someone using onboard gpu for example and 8gb ram

rocky canyon
void shell
rocky canyon
#

ive seen people with local cursor lag..

#

that still used unity..

#

thats commitment

void shell
#

it's an galaxy book go (4gb ram, snapdragon7c gen 2 ARM)

rich adder
#

just realized we should probably make a thread or sumawkwardsweat going offtopic from code

void shell
#

FOR REAL

rocky canyon
#

how come ive never heard of a mediator pattern 🤔

#

its actually probably something ive used or seen used and didnt know it had a name

rich adder
#

tbh most of these patterns I was doing without knowing a name to it

gleaming haven
#

hey i just stumbled upon unity, can anyone recommend a good yt tutorial playlist to get started with? i only found really old ones

void shell
void shell
rich adder
#

eh I think for a beginner code monkey is a bit much

void shell
#

meh, fr

rich adder
#

his code is confusing as hell sometimes and you yell at the screen "WHY"

#

also the cringe earlier videos where he uses his own UTILS you have to download from his sketchy site lol

void shell
#

i started with "Crie Seus Jogos" that is a brazilian channel yk? the guy talk to you like he is teaching a dog, impossible to not learn

rich adder
#

I started with earlier vids of Jason Wiemann they were pretty solid

rocky canyon
#

if he ever decides to edit out his Mechanical keyboard rather than emphasize it i'll consider watching his coding stuff

#

until then i'll just check out his Monthly asset list/review vids

rocky canyon
#

actually tbh, those were the only two household names i used to learn almost everything i needed to know..

rich adder
#

yah those are the good OGs
seb is more of devlog now so he doesnt always show the complete code but gives nice inspirations

rocky canyon
#

ahh yea i do use this design pattern.. well i'l be darn knee slaps

rich adder
#

yeah its pretty common once you see it in action. The real world analogy for it is perfect

#

that + observer pattern (just events lol)

rocky canyon
#

but mine is a level above the game manager..

#

so it'll get its info from teh game manager to know whether or not to call functions in the game manager..

#

which at first kinda put me off from using it

#

but im sure theres another little workflow trick i dont know about to remedy that.. or make it make more sense i just havent discovered it yet

rich adder
rocky canyon
#

also its kinda how i got my "References" object set up

#

the actual manager was getting too big and knowing about too many things

#

so i subdivided the data type stuff

rich adder
#

also i don't typically make 1 giant mediator for many things (or you're back to GM monoliths), I more or so categorize them, also a bit of chain of responsibility parts

sour fulcrum
rich adder
#

Debug Mode 😛

slender nymph
#

it's pretty easy to just write your own ReadOnly attribute and property drawer

sour fulcrum
#

i knowwww

#

but like

#

tell unity that 😛

rich adder
#

Unity is just lazy esp if there are assets for it

rocky canyon
#

i used to use naughty attributes so i had alot more read-only fields and stuff

rich adder
#

imagine how easy it would be for unity to make something like Naughty or Odin

rocky canyon
#

but something about it broke my frame rate a while back and i couldn't save the project

#

so since then i wont install naughty

#

i just write my own attributes

#

like these cute little icons 😊

sour fulcrum
#

serialize a dictionary or lay off staff
unity: 🤔

rich adder
#

priorities mannn

idle grove
#

heya, i have a ''random'' question!

#

using public variables for ''universal'' things, such as object speed and such, is a bad idea right, so it is usually private, and at max a [serialized field], but what if i want certain objects to have these variables tempered with? like buffs, debuffs n such.

would doing a private generic variable (private float moveSpeed; for example) for every entity that has it.
but then doing a public specific variable (public float playerMoveSpeed; for example) and then set playerMoveSpeed = moveSpeed;
would it work? cuz that way i can change this public variable to for example:

playerMoveSpeed = moveSpeed * SpeedBoost

using another script, would that work? is that dumb? is that unstable?

rich adder
sour fulcrum
#

so the real kinda answer for this is c# properties but in general the idea is you want a public facing way to try and set the value, and let that function decide if the incoming value is ok to be used

#

the issue with public fields directly is any random stranger and give it any random value

#

your fine having a stranger do it but you need to check if the value is ok

rich adder
#

yeah public fields can really trip your future self or another person working on it

idle grove
#

im still a super beginner so i dont have the knowledge baggage to know better ways, im sorry for that, i will take a look into learning those things to see if i comprehend it tho!, this was the way i thought about based on what i know (super super beginner)

idle grove
sour fulcrum
#

yeah no stress, you know what functions are right?

rich adder
#

properties / functions generally the best way so you can put things like notifications of values changed and stuff like that

rocky canyon
#

i use an SO with all my player data (default values).. and then it'll read em and assign em all to a local version of that variable.. (those i can modify as i wish all i want in the inspector, runtime or w/e) when the game restarts my default values are still intact

#

if i want to keep a modified value or something ill just jot it down

idle grove
sour fulcrum
#

your not wrong in thats what they do but a function in the context of programming conversations is literally just a

void MyFunction()
{
stuffs
}

idle grove
#

yeah, learned that doing a function to flip the character on the X axis, in that case, void Flip()

rich adder
#

functions and methods are generally interchangeable but functions are usually the "doing something" that function on their own, methods are associated with objects

idle grove
#

just so i get it as a direct answer, was the thing i described wrong?, or just not optimal/has a specific problem?

#

i couldnt find it when i tried searching about this method

rocky canyon
#
        int currentHealth;
        public int Health
        {
            get => currentHealth;
            set
            {
                // Clamp value between 0 and maxHealth
                currentHealth = Mathf.Clamp(value, 0, maxHealth);

                // Check for death
                if (currentHealth == 0)
                    Debug.Log("💀 Player Died");
            }
        }

        public void Damage(int amount)
        {
            Health -= amount;
        }

        public void Heal(int amount)
        {
            Health += amount;
        }```
#

so whats a property do? is it a function?

sour fulcrum
#

probably dont need to hit the property off the bat

rich adder
#

they do have a flip bool on sprite renderer and such, but the method usually something you write

rocky canyon
#

i just lookin around for some use-cases that make me stop and refactor my code b/c i can't go without properties a minute longer 😅

idle grove
#

property i still didnt learned, im sorry, what i can imagine is that it ''reads'' functions/manages them in some way? like add a property to adress X and Y functions in some way ? but at this point id be guessing

rocky canyon
#

b/c ngl, ive neglected them for a long time now

idle grove
sour fulcrum
#
    public class MyClass : MonoBehaviour
    {
        [SerializeField] private int currentHealth;
        [SerializeField] private int maxHealth;

        public int GetCurrentHealth()
        {
            return (currentHealth);
        }

        public void SetCurrentHealth(int newHealthValue)
        {
            if (newHealthValue > 0 && newHealthValue < maxHealth)
                currentHealth = newHealthValue;
        }
    }

@idle grove so this is a very basic example of what you would ideally want to do instead of having the field be public directly

don't worry about using properties specifically for now they are just a convient way to merge functions and fields, ignore them

idle grove
#

thats what i meant with learning it, i learned how to do a function, and named it flip, to use on the player movement

sour fulcrum
#

the idea with this code is that you can control what the value can actually be set to when strangers try to tamper with it

rich adder
#

slap a OnHealthChanged Action<int> and you're golden
this way if others want to react when it changes its easy to do

polar acorn
sour fulcrum
#

Or as nav said previously, you also get to know when it does get tampared with, in case you need to run code in reaction to the change

idle grove
#

im slowly getting it

#

thanks people

#

i still have to get more of the basics to fully get it, but atleast it doesnt feel like magic

sour fulcrum
#

idk if this is a psycho comparison but imagine that

a public field is like a gold bar teleporting into a bank vault

a public function is like someone actually walking into the vault and putting the bar in there

rich adder
rocky canyon
#

the way i think of it now is
you can use OnValidate() method to check if a variable ur entering into the inspector is a valid one..
but that only works in edit mode..
you can use a property to check if a variable either you entered or a script tried to set is a valid one..
and that works at Runtime

#

and.. theres all kinda cool things u can do with the getter and the setter.. making one public one private.. as nav just said and so on

sour fulcrum
rocky canyon
rich adder
#

im crazy but I always give it a private field / backing field

rocky canyon
#

never looked back 🤣

idle grove
# rocky canyon

asking for pure curiosity, this is from what type of project that you're doing ?

sour fulcrum
rich adder
#
public int Value => myValue;
[SerializeField] private int myValue; //or no serializefiled sometimes```
rocky canyon
idle grove
sour fulcrum
#
public string Message
{
    get;
    set => field = value ?? throw new ArgumentNullException(nameof(value));
}

14 lets you do this 😄

rocky canyon
rocky canyon
#

and easy to see things at a glance

#

if all ur values start at 0 u cant mess any of them up 🫠

naive pawn
rocky canyon
#

lol true

#

i have tons of backups of this guy

rich adder
#

using structs for this is annoying in unity we cannot assign default values..this is the shit that irks about old C#

rocky canyon
#

on scratch paper, in screenshots, everywhere

#

lol

rocky canyon
rich adder
#
public struct Data{
public int speed = 10; // unity cries
}```
naive pawn
#

i mean you can do something like this though, no?

public X x = new("default");

[Serializable] public struct X { public X(string n) { this.n = n; } public string n; }
rocky canyon
#

got my structure at the bottom and the default ones at the top

rich adder
naive pawn
#

ah. you can do spawn's thing with the bracket init though

sour fulcrum
#

assign all these values immediately without using functions or i will KILL MYSELF

rocky canyon
#

that was sooo hard for me to read

naive pawn
#

my codegolf blood is showing

rocky canyon
#

i wish i could read it better

naive pawn
#

i tend to just... ignore the existance of newlines when doing small tests like that yeah lmao

rich adder
#

yeah took a couple passes to read lol

rocky canyon
#

i love army acronyms and i wish i could code using more acroynms 😈

naive pawn
#

hey aren't colliders supposed to use green lines

rocky canyon
#

typically yea

naive pawn
#

so my monitor just decided to pull an optical illusion on me i suppose
the boxcolliders i had looked like they had green horizontal lines and white vertical lines

#

zoomed screenshot/other monitor showed consistent green

obtuse basin
#

nah ur just hallucinating

#

happens sometimes

sour fulcrum
#

any chance you have two gizmos lines drawing the same place and the load order sometimes flickers?

naive pawn
#

no, i think it (gpu/monitor, idk) decided the line was too thin and actually did just make it white

sour fulcrum
#

honestly so valid

naive pawn
#

oh wait this is the code channel. whoops.

wise cairn
#

ok so guys i read this C# crash course, do you think that's enough tp start making basic games or should i do more

naive pawn
#

that's not a very answerable question

#
  • depends on what you mean by "basic"
  • make sure you also understand it, not just that you read it
  • you'll also need to learn unity apis and messages
  • you'll also need to learn how to use the unity editor, how to work with gameobjects, and how to manage the assets
  • you won't remember all of it, make sure you can find what you need if you have to go back to check
#

that being said - sure, you can start making stuff, but don't do "learning" and "making" as separate steps
learn as you go too, via tutorials, via guides, via docs, etc

wise cairn
#

ok got it

#

where can i find resources for learning unity stuff

rotund hull
#

I am trying to make a crafting interface in my survival game and used a scroll view for it. But when you select the scroll bar with your mouse and use it you can controll it with w and s, how can i remove this

eager elm
rotund hull
mossy jasper
short hazel
#

Use GetAxisRaw instead, as GetAxis smoothes out your inputs from 0 to 1 and back

#

The effect is that, because you normalize the vector made for these inputs, it'll keep going until your inputs are both exactly 0, which takes a second or so with GetAxis

mossy jasper
#

thanks

twin pivot
eternal falconBOT
short hazel
#

You still need to normalize the vector in order to go the same speed diagonally, idk why you removed that part

vocal wharf
#

I'm still having problems with my game 🤦‍♂️. I want my player to be constantly upright relative to the sphere so that the feet are on the sphere no matter the position on the sphere. I've gone through so many tutorials and docs and this is what I have so far. The player is locked to what seems like global "uprightness" if that's a word. It's not rotating with the curve of the sphere, only staying vertical. Even after rotating the player using the editor during play mode, it just snaps back upright. I've used debug raycasts for the different vectors and gravity is pointing at the center of the sphere as it should but the player vector is locked upright. Any help is appreciated.

public class Gravity : MonoBehaviour
{
    public Rigidbody[] rigidBodies;
    public GameObject planet;
    private Vector3 gravityVector;
    private Vector3 rigidBodyVector;
    public float gravityStrength = 1f;
    public float rotationSpeed = 10f;
    void FixedUpdate()
    {
        foreach (Rigidbody rb in rigidBodies)
        {
            gravityVector = (rb.transform.position - planet.transform.position).normalized;
            rigidBodyVector = rb.transform.up;
            Debug.DrawRay(rb.transform.position, gravityVector, Color.green);
            Debug.DrawRay(rb.transform.position, rigidBodyVector, Color.blue);
            rb.AddForce(gravityVector * -gravityStrength);
            Quaternion currentRotation = transform.rotation;
            Quaternion targetRotation = rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector);
            rb.transform.rotation = Quaternion.RotateTowards(currentRotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
        }
    }
}
mossy jasper
#
    {
        float moveX = Input.GetAxisRaw("Horizontal"); //A / D movement or left / right
        float moveZ = Input.GetAxisRaw("Vertical"); // W / S movement or Up / Down

        Vector3 move = new Vector3(moveX, 0f, moveZ).normalized * moveSpeed;

        //move the player
        Vector3 velocity = new Vector3(move.x, rb.linearVelocity.y, move.z);
        rb.linearVelocity = velocity;
    }
}
twin pivot
vocal wharf
hollow slate
mossy jasper
twin pivot
#

why are interfaces stored in the transform of a GameObject?

slender nymph
#

what do you mean by that?

twin pivot
#

for example when you get a class from a gameObject you do gameObject.GetComponent<MyClass>(); but for interfaces you do gameObject.transform.GetComponent<IMyInterface>();

slender nymph
#

interfaces are not "stored" anywhere. and using GetComponent to find a component with a specific interface works exactly the same as finding a specific component class

sour fulcrum
#

(it's not stored period as you mentioned but in the context of how the question is phrased it is "stored" on the component that implements it)

twin pivot
#

oh so it's just gameObject.GetComponent<IMyInterface>();?

sour fulcrum
#

oh yeah the transform getcomponent just is a quality of life pointer to that iirc

#

since the transform <-> gameobject relationship is mandatory there's a couple functions that are provided in both

slender nymph
#

GameObject and Component both have a GetComponent method that works pretty much exactly the same. which is why you don't ever need to specifically access an object's gameObject or transform property to call GetComponent, you can call GetComponent directly on that object (assuming the object in question is a GameObject or Component)

twin pivot
#

Thanks for the help (kinda just excited with how easy interfaces make things happen)

sour fulcrum
#

oh yeah interfaces can be really nice

#

since you can try and get just that seperate chunk of functionality without caring about whatever else is there

twin pivot
#

regret skimming over it last time, would've made things so much easier

sour fulcrum
#

just makes using them now more rewarding 😄

#

they can be easy to over-use in some cases though but just takes abit of practice to figure out when and when not to use em

#

interfaces with constrained generics can get psycho fast lol

twin pivot
#

how do you even read that? I have enough problems with nested code lol

sour fulcrum
#

i poke at it until the red goes away

twin pivot
#

absolute nightmare fuel

solemn arrow
#

I have no idea where else to ask this, but for some reason the origin point for my player is wayyyy off in the distance from where its supposed to be due to the UI being parented under the player, issue is that I need the origin point to be proper since im trying to get the camera to look at something

#

so is there a way I can fix this? I'm trying to use Quaternion.LookRotation since it allows me to use Lerping

slender nymph
#

make sure your tool handle is set to Pivot not Center so it shows on the actual origin point of the object selected and doesn't approximate a center based on the object and its children

solemn arrow
#

Ah that fixed it very quickly, thanks

#

well in the editor I mean

#

there is definitely an issue with my code, but im not quite sure what 🤔

slender nymph
solemn arrow
#

Ohhhhhhhhhhhh, I thought it worked as a way of retrieving a rotational value, so i was using it in substitution to Transform.LookAt

#

since I needed to smooth the camera's rotation rather than having it immediately snap

slender nymph
#

no, if you just want the target's forward direction then use target.transform.forward.
otherwise direction is (endPosition - startPosition)

solemn arrow
#

Thanks! that fixed it

digital haven
#

Question. I want to use other models since mixamo isn’t letting me install non in place models I need.

Where can I get something similar that will work just as well?

slender nymph
#

this is a code channel

acoustic belfry
#

hey, for make a cast for detect the floor, wich shape is best in 2d, a square or a circle?

acoustic belfry
#

i forgot, thanks

mossy jasper
frosty hound
#

Pause the game whenit happens and select one of those bricks. Where is located in your hierarchy, is it a child of something like the player/camera?

mossy jasper
#

yeah, most of the bricks are linked to the player, so how to ffix?

frosty hound
#

Don't put them as a child of the player? I mean, that would be the obvious answer here.

#

You clearly succeeded in doing that with half your bricks already.

past yarrow
frosty hound
#

So select the bricks, drag them out of your player in the hierarchy.

mossy jasper
#

ok

wise cairn
#

ok so guys i'm making a super simple platformer to learn unity because i haven't really used it before

#

and i'm trying to add a script for player movement and i have absolutely no idea what to do

#

i assume i need to learn some unity code things?

frosty hound
#

Well, yes, Unity isn't going to do it for you.

#

You can start with the !learn tutorials.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wise cairn
#

thank you

unique quartz
#

I'm making these rabbits move by themselves with simple ai, but their idle animations dive into this, then dive back up to normal when they run. Disabling root motion stopped them from diving down, but it altered their movement and made them slow

#

i will also add they float in game mode but don't in scene mode

burnt vapor
#

If you think the issue is related to !code, please share it

eternal falconBOT
unique quartz
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class AI_Movement : MonoBehaviour
{

    Animator animator;

    public float moveSpeed = 0.2f;

    Vector3 stopPosition;

    float walkTime;
    public float walkCounter;
    float waitTime;
    public float waitCounter;

    int WalkDirection;

    public bool isWalking;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();

        //So that all the prefabs don't move/stop at the same time
        walkTime = Random.Range(3, 6);
        waitTime = Random.Range(5, 7);


        waitCounter = waitTime;
        walkCounter = walkTime;

        ChooseDirection();
    }

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

            animator.SetBool("isRunning", true);

            walkCounter -= Time.deltaTime;

            switch (WalkDirection)
            {
                case 0:
                    transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
                    transform.position += transform.forward * moveSpeed * Time.deltaTime;
                    break;
                case 1:
                    transform.localRotation = Quaternion.Euler(0f, 90, 0f);
                    transform.position += transform.forward * moveSpeed * Time.deltaTime;
                    break;
                case 2:
                    transform.localRotation = Quaternion.Euler(0f, -90, 0f);
                    transform.position += transform.forward * moveSpeed * Time.deltaTime;
                    break;
                case 3:
                    transform.localRotation = Quaternion.Euler(0f, 180, 0f);
                    transform.position += transform.forward * moveSpeed * Time.deltaTime;
                    break;
            }

            if (walkCounter <= 0)
            {
                stopPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
                isWalking = false;
                //stop movement
                transform.position = stopPosition;
                animator.SetBool("isRunning", false);
                //reset the waitCounter
                waitCounter = waitTime;
            }


        }
        else
        {

            waitCounter -= Time.deltaTime;

            if (waitCounter <= 0)
            {
                ChooseDirection();
            }
        }
    }


    public void ChooseDirection()
    {
        WalkDirection = Random.Range(0, 4);

        isWalking = true;
        walkCounter = walkTime;
    }
}```
unique quartz
#

i fixed it by freezing x and y rotation

vocal wharf
#

I've been stuck on this problem for days so any help would be nice. I'm trying to get all rigidbodies in the array to stand upright relative to the curve of the sphere (planet) and rotate to be perpendicular to the sphere no matter their position on the sphere. I've read all kinds of docs and tutorials and I feel like this should work but it permanantly locks the rigidbody (player) to global vertical and it doesn't even let me rotate the player on its Y axis (basically making so I can't turn side to side). Any ideas what's wrong?

public class Gravity : MonoBehaviour
{
    public Rigidbody[] rigidBodies;
    public GameObject planet;
    private Vector3 gravityVector;
    private Vector3 rigidBodyVector;
    public float gravityStrength = 1f;
    public float rotationSpeed = 10f;
    void FixedUpdate()
    {
        foreach (Rigidbody rb in rigidBodies)
        {
            gravityVector = (rb.transform.position - planet.transform.position).normalized;
            rigidBodyVector = rb.transform.up;
            Debug.DrawRay(rb.transform.position, gravityVector, Color.green);
            Debug.DrawRay(rb.transform.position, rigidBodyVector, Color.blue);
            rb.AddForce(gravityVector * -gravityStrength);
            Quaternion currentRotation = transform.rotation;
            Quaternion targetRotation = rb.rotation * Quaternion.FromToRotation(rigidBodyVector, gravityVector);
            rb.transform.rotation = Quaternion.RotateTowards(currentRotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
        }
    }
}
#

this is the gravity/rotation script that's on the planet object

wintry quarry
#

shouldn't that just be rb.rotation?

vocal wharf
#

I missed that

wintry quarry
# vocal wharf oh shoot yes thanks for pointing that out

This also looks backwards:

gravityVector = (rb.transform.position - planet.transform.position).normalized;```
As you would expect gravity to point at the center of the planet, not the other way around, although you appear to be adjusting for that in your other code with the -gravityStrength
vocal wharf
#

hmm ok

vocal wharf
wintry quarry
#

I mean yeah you have two different scripts trying to control the rotation of the object

#

they are going to conflict

#

Also this code:

transform.Rotate(transform.rotation.x, mouseX * mouseXSens * Time.deltaTime, transform.rotation.z);```
#

is very very wrong

vocal wharf
#

oh?

wintry quarry
#

This is what you want:

transform.Rotate(0, mouseX * mouseXSens0, 0);```
vocal wharf
#

hmm ok

naive pawn
#

transform.rotation is a quaternion, you don't want to access individual members

wintry quarry
#
  1. Tiem.deltaTime should not be used with mouse input
  2. transform.Rotate is relative, you would not put the current rotation in there
  3. .rotation is a quaternion yeah
sour vessel
#

Guys do you think Chat GPT is right about this one? My concern is, linear velocity should be towards Y axis. I'm so beginner at game development and coding so maybe I horribly missed something
Here's the script im using:

using UnityEngine

public class PlayerMovement : MonoBehavoir
{

        [SerializeField] private float speed;
[SerializeField] private float jumpHeight;
[SerializeField] private float dashSpeed;

private Rigidbody2D body;

private  void Awake()

{

body = GetComponent<Rigidbody2D>();

Unity Messag sage 10 references

private void Update()

Float horizontalInput Input.GetAxis("Horizontal");

body. LinearVelocity = new Vector2(horizontalInput speed, body. LinearVelocity.y);

// making the player flip when moving Lef-Right

if (horizontalInput > 0.01F)

transform. localScale = new Vector3(6.5f, 1.25f, 0.5f);

else if (horizontalInput < -0.014)

transform.localScale = new Vector3(-0.5f, 1.25f, 0.5f);

// Jumping Input

if (Input.GetKey(KeyCode. Space))

body. LinearVelocity = new Vector2(body. LinearVelocity.y, jumpHeight);

// Crouching Input

if (Input.GetKey(KeyCode.S))

else

transform. localScale = new Vector3(0.5f, 0.5f, 0.5f);

transform.localScale new Vector3(0.5f, 1.25f, 0.5f);

if (Input.GetKey(KeyCode.5))

else

GameObject.Find("Player").GetComponent<Renderer>().material.color = new Color(1, 0.64765a8f, 0);

GameObject.Find("Player").GetComponent<Renderer>().material.color = new Color(8.88856554, 8.8962266, 0);

// Dashing Input

if (Input.GetKey(KeyCode. LeftShift)) body. LinearVelocity= new Vector2(bedy. LinearVelocity.x, dashSpeed);```
wintry quarry
#

there were many things wrong with that

naive pawn
#

Chat GPT is right
yeah just don't put those 2 words in the same sentence

wintry quarry
#

in this case

#

you can also just do body.velocityY = jumpHeight;

naive pawn
#

chatgpt is not fully correct

wintry quarry
#

although jumpHeight is an innacurate name for what that variable is doing

sour vessel
naive pawn
#

linearVelocity is not from visual scripting, it is the new name for velocity

naive pawn
wintry quarry
#

oh yeah I didn't notice that part

naive pawn
#

also yeah that code is... frankly horrendous

#

there's so many errors

wintry quarry
#

there's no way it compiles

sour vessel
naive pawn
#

incorrect syntax, misspelt props, incorrect casing, invalid identifiers

wintry quarry
sour vessel
#

It's the force

#

Right?

wintry quarry
#

It's not a force

#

it's the velocity you are setting

#

it means you will start moving upwards at 5 meters per second. You will then follow a parabolic curve eventually landing back on the ground.

naive pawn
#

it's more of an impulse that doesn't care about mass

wintry quarry
#

the height you reach will not be 5 meters

#

Note:
The result of applying a force is to change the velocity of an object

#

you are doing the same thing a force does, but skipping actually using a force

vocal wharf
wintry quarry
#

everything is possible

vocal wharf
#

I just don't know where to start

sour vessel
naive pawn
#

velocity is a speed with a direction

sour vessel
#

Ooooh alright

#

I know about it but only in my language

sour vessel
naive pawn
#

a starting velocity of 5 with a gravity of 10 will reach a height of 1.25

naive pawn
sour vessel
naive pawn
#

did you retype the script

#

ah well that makes sense since you said you didn't have discord on pc

#

yeah don't do that, ever

sour vessel
#

Any typo in the script is actually google lens fault not mine

naive pawn
#

it is your fault by using google lens lmao

#

you created 21 errors by doing that

#

just copy and paste the script

#

don't retype code or errors when sharing them, period

sour vessel
#

Anyways there's something I wanna understand

#

1-"linearVelocity.y" needs to be changed to "... .x" cool but shouldnt it be the Y axis? Like you're jumping vertically through the Y axis

naive pawn
#

you want to change the y axis, you want to preserve the x axis

wintry quarry
#

you are creating a number here, which will be the new velocity of the object:
(x, y)
what you want is:
(current x velocity, new jumpy y velocity)

#

what you had before was:
(current y velocity, new jumpy y velocity)
Which makes no sense and now you're making the object move sideways at the speed it was moving up/down at.

sour vessel
#

Alright i got it now

#

Gonna test it then im gonna go back here to ask about the other issues
I need someone patient

naive pawn
#

take a screen recording, not a recording of a screen

sour vessel
#

Wait

#

I can use usb to transfer file

#

Sht mb wait a min

frail hawk
#

i don´t know what is more annoying, the recording of the screen with a mobile phone or that the screen is upside down

sour vessel
#

When i hold the space button the player FLIIIIES

naive pawn
#

use mp4 so it embeds on discord

naive pawn
#

use GetKeyDown to trigger only on the frame it's pressed

sour vessel
#

Alriiiight

#

Now i have problem with crouching

#

When i press S the player gets slightly above the ground then drops down

naive pawn
#

that's not an acceptible form

#

copy and paste your code, don't use google lens

sour vessel
#

I completely forgot I can transfer files from phone to pc via usb

naive pawn
#

!code

eternal falconBOT
strong shoal
#

public class EnterCommand : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI commandField;
private Dictionary<string, Action> _commands;

private void Start()
{
    _commands = new Dictionary<string, Action>()
    {
        { "test", Test }
    };
}

public void CommandEntered()
{
    String command = commandField.text.Trim().ToLower();
    
    if (_commands.ContainsKey(command))
    {
        _commands[command].Invoke();
    }
    else
    {
        Debug.Log($"There`s no command named: {command}");
    }
}

private void Test()
{
    Debug.Log("test");
}

}

#

can someone tell me why its displaying that there is no command names test

slender nymph
#

is commandField perhaps part of a TMP InputField? if so this might be the u200b character causing issues

strong shoal
#

ohhh

#

that would make sense

slender nymph
#

refer to the TMP_InputField directly not the TMP_Text it modifies

strong shoal
#

UR THE BEST

#

THX A LOT

chilly prism
#

guys i need help with the canvas gameobject

#

how do i get rid of these white lines

naive pawn
rocky canyon
#

thats at the very bottom left corner of ur screen

#

ull only see the edge of that number

naive pawn
chilly prism
#

both

cosmic quail
rocky canyon
#

i usually Hide the canvas components

chilly prism
#

how

naive pawn
chilly prism
naive pawn
#

any suspicion at all what it could be from?

rocky canyon
slender nymph
#

note that gizmos like the canvas bounds are only ever shown in the editor. it should also not even be possible to see that in the game view considering it would be bordering the screen

rocky canyon
#

can u even hide that? i never knew u could

chilly prism
slender nymph
#

that small rectangle is your camera. the big one is the canvas because it is a screen space overlay canvas

rocky canyon
#

same here

chilly prism
slender nymph
#

you don't need to