#💻┃code-beginner

1 messages · Page 753 of 1

meager flume
#

using this

edgy sinew
#

I think you can accomplish it with these parameters

float baseJumpImpulse = 20.0f;
float maxAddedJumpForce = 10.0f;
float timeToWaitBeforeAddingForce = 0.04f; // delay before adding jump - optional
#

The thing is, to prevent "press jump button, release, then press again and start adding force"

#

So you have to coordinate that, I'd think started performed canceled will be useful here

tender mirage
#

Is there an reason my class isn't appearing in the inspector

//Player DebugUI
[System.Serializable]
public class PlayerDebugUI : PlayerScript
{
    public TextMeshPro PlayerVelocityText;


    private void FixedUpdate()
    {
        
    }




}
edgy sinew
#

PlayerScript

    [SerializeField] myPlayerDebugUI PlayerDebugUI;
tender mirage
#

will try it out right now

wide aspen
tender mirage
#

but that wont work

#

i assume

edgy sinew
#

Also why is it a child of PlayerScript? 🤔

#

What is the goal with this overall?

tender mirage
#

from the playerscript

#

and to do that making it the child saves me from requiring it

edgy sinew
#

So... PlayerDebugUI is a MonoBehaviour too.

#

You can't rly get the variable that way - it needs access to the instance of PlayerScript component kekwait

tender mirage
#

Whaat?! i thought you could

#

since it's a child

#

it would just recognize the parent variables

edgy sinew
#

There's much better ways to "share variables" that's all

#

You don't want to be inheriting that whole thing though.

#

Just add the require component, then GetComponent in Awake, and access the variable. 🤷‍♂️
Or keep that variable as a Scriptable Object and there are easy ways to access it from wherever.

tender mirage
#

Are you refering to static's?

#

i've tried them out. but my last project were really, i mean really unorginized in some areas

edgy sinew
#

It's not needed, component instances can talk to each other easily

#

"Shared data" is a common topic in Unity ... easy to find on Google

tender mirage
#

That's an fair point.

#

i guess i should just really be reading other peoples conversations,.

edgy sinew
#

Scriptable Objects are nearly identical to MonoBehaviour, except they live in a Folder in your project, rather than on a GameObject in the Scene

#

yeah this topic has been crossed before for sure

tender mirage
#

That sounds very important for larger and good orginizations

edgy sinew
#

Besides my own experiences, I'm basically just telling you everything I've read online about it 🗿

scarlet pasture
#

can i write Methods in SO? and use them in other Scrpts? like APIS (is the Player Moving etc..)?

tender mirage
#

💀

scarlet pasture
#

and is this a good way because i write all apis in my Player Movement Script

#

like SlowForTime.

edgy sinew
#

ScriptableObjects are like MonoBehaviours except they exist outside of a Scene. They live in your project, like data, rather than a behaviour, which is in the scene. ScriptableObjects don't get events like Update().

tender mirage
#

i've modded some games before, and their scripts are orginized in folders, i need to learn scriptables at once

scarlet pasture
#

so? i can write Methods for the Player? i assume

edgy sinew
#

It's not valuable, but it's possible

scarlet pasture
#

so its just better if i use it on the normal Scripts?

edgy sinew
#

MonoBehaviour gets all the callbacks. ScriptableObject is mostly for storing data that can be easily accessed project-wide.

#

Or for configuration - they hold their values when Playmode ends, unlike Serialized fields.

#

For example you'd rather have a ScriptableObject for tuning your character. Movespeed, rotation speed, jump height, strength of gravity, etc

#

When you have a configuration you like, you can just duplicate that ScriptableObject asset file, and then it's there whenever you wanna switch back.

#

@tender mirage @scarlet pasture simple example


[CreateAssetMenu(fileName = "PlayerRuntimeStats", menuName = "Scriptable Objects/PlayerRuntimeStats")]
public class PlayerRuntimeStats : ScriptableObject
{
    [HideInInspector] public Vector3 position;
    [HideInInspector] public Vector3 velocity;
}

Now in your MonoBehaviour, you can just reference an instance of these stats (created before runtime, either find by name or drag & drop by serializing), or create one at runtime and put it in a location you will access from other scripts.

Unity keeps track of whatever folder you name "Resources" so that can be a fine place for that kind of thing.
But it's easier to just create the object beforehand - unless you have multiple players (co-op) or something like that.

tender mirage
#

✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=7jxS8HIny3Q
Let's learn all about Scriptable Objects and how they help us make our Games Designer Friendly!
👇
🌍 Get Code Monkey on Steam!
👍 Interactive Tutorials, Complete Games and More!
https://store.steampowered.com/app/1294220/

Make your Games De...

▶ Play video
#

i was just watching the tutorial

#

it looks incredibly useful

#

i gotta admit

edgy sinew
#

Avoid CodeMonkey, he writes really careless & wrong code

tender mirage
#

I generally avoid tutorials

#

don't worry about that.

#

although.. i do get stuck sometimes on silly things.

scarlet pasture
#

even cant*Ü

tender mirage
#

yeah, although tutorials aren't even the worst nightmare anymore

#

traps like ai are most more harmful and there are geniunally people that fall for it.

scarlet pasture
#

Definetly

#

this is way i ask here ervthing like last time i didnt even know how to set up a Vector to the Player and asked here

#

and also reading docs

#

i try to learn the Code by doing it reather than asking Ai, i think this can help me to understand the Code better

tender mirage
#

Y'know the feeling of just solving problems. it's great

#

And yeah, you get much better muscle memory

#

by trial and error

#

rather then asking some statistical machine to generate answers

frozen crypt
#

can someone help me with AI Navigation, i have tried basically everything and i cant find out how to make my AI stop hugging walls

slender nymph
frozen crypt
#

ok ig

#

So uhm my AI hugs walls in hallways. Heres my script: https://paste.mod.gg/rrzcqrbpywcq/0 I’m using a NavMeshSurface and NavMeshAgent, step based movement, agent radius 0.65, and hallways ~5 units wide. Tried center offsets but it still touches walls.

scarlet pasture
#

does that work in unity?

frozen crypt
#

yea

scarlet pasture
#

wow

frozen crypt
#

im used to print more

#

than Debug.Log

#

so i use print

scarlet pasture
#

is that better?

frozen crypt
#

its the same

scarlet pasture
#

its faster for typing haha

frozen crypt
#

just faster to write and better to memorize for me

#

yea well it works the same as Debug.Log

scarlet pasture
#

i wish i can help u but im to bad hah

frozen crypt
#

one time i just wrote print as a joke and then tested it and it worked

scarlet pasture
#

on this day im also starting using print haha

frozen crypt
#

yea well my Only issue is AI Navigation stuff bc this AI keeps kissing walls and wont stop

scarlet pasture
#

but can u say Debug.LogError

frozen crypt
#

i didnt even know that existed tbh

scarlet pasture
#

i used it all the time

#

or Debug.LogWarning

scarlet pasture
#

i only used one time so i dont know really

frozen crypt
#

i already tried everything possible

rich adder
hallow acorn
#

does someone know what could cause these hard edges between my chunks? the y levels are generated using the same noise algorithm and should be equal

willow lodge
#

Hey everyone im trying to make a mouse over object detection script but when i hover the mouse over the instance of the object it gives me "Object reference not set to an instance of an object" error anyway to solve this error?
I also wanted to say that the script works normally on the original object and only gives this error with the instances of the object

willow lodge
#

Ok

willow lodge
#

Dont mind the mouse over script

rich adder
# willow lodge

you need to expand the Console window and show which line # is the Null Reference Exception

#

also don't send video/screenshot of code. Use pastebin links 👇

#

!code

radiant voidBOT
willow lodge
rich adder
willow lodge
#

Ok sure

willow lodge
#

Like this?

rich adder
#

yea

willow lodge
#

I also used ai for the code sooo

rocky canyon
#

probably shuldnt have said that

willow lodge
#

Idc

rocky canyon
#

now no ones gonna wanna help you..
if u didn't write ur own code and don't understand what the chatbot gave u.. what makes us think you'll understand the solutions for it 🤔

rich adder
#

I can tell by the unicode chars in the comments..

wild peak
slender nymph
#

it's against server rules to not disclose that, so it's better that they actually admit it instead of trying to be cheeky about it

willow lodge
rich adder
#

at the very least you have to understand what the code is doing and what the lines means, otherwise any suggestions to a fix will be moot

rocky canyon
#

^ this is basically what i was sayin

willow lodge
#

I understand some of the code

rocky canyon
#

ill bite

#

so none of ur Mouse functions work?

rich adder
#

Ima take a wild guess its probably selected throwing NRE but without seeing the line its a guess

rocky canyon
#

☝️ same

rich adder
#

for all we know it could also be Camera.main or another script :\

willow lodge
#

You ppl can understand what im trying to make from the code right?

rocky canyon
#

selectedObj is a cheeky script name 😅

willow lodge
willow lodge
rocky canyon
#

what do you mean by "you people".. 🤣 yea we sorta guess

onMouseEnter u set selectedObject's selectedObject variable to 0

#

onMouseExit sets it to 1

thorn holly
radiant voidBOT
willow lodge
rocky canyon
#

its rather confusing b/c selected.selectedObject = 0;
is basically the same as selectedObj.selectedObject which is confusing just a bit

willow lodge
#

Yep i know

rocky canyon
#

the naming would help a lot.. but u get better at naming as u go..

#

u said ur just 1 week in.. soo i wont hold it against ya lol

willow lodge
#

I used scriptable objects for global values

rocky canyon
#

just had to clarify

#

log selected in ur Functions to make sure its assigned

rocky canyon
#

or just check the inspector

rich adder
#

also you outta check the lines number on the nre

rocky canyon
#

ya, something is not assigned which is what null is

willow lodge
#

I shoud just rewrite the script😓

rich adder
#

for all we know its an entirely different script..

rocky canyon
#

"use this reference".ToDoThisThing();
but the ide is like "that reference isn't referenced"

rocky canyon
#

don't continue until u get the basics working

willow lodge
#

Ok sure

rocky canyon
#

once it works its repeatable..

#

if u do it all at once and it doesnt work.. its much harder to figure out where it went wrong

#

especially when learning

#

should take small bite sized pieces

rich adder
rocky canyon
#

maybe call the script SelectionManager

#

and the variable currentSelection

willow lodge
rich adder
#

looks like the SO is only assigned to the Instance in the scene and not the original prefab

willow lodge
rich adder
#

then its probably not assigned in the original prefab

#

as indiecated by the "bold" text and blue line next to the name

rocky canyon
willow lodge
rich adder
willow lodge
rich adder
#

the scriptable object..

#

the only thing that I said was clearly only assigned to the Instance in the scene.

rocky canyon
#
    if (selected == null)
    {
        Debug.LogWarning($"selected is NULL on {gameObject.name}", this);
        return;
    }``` ^ you can actual put null checks *in* the code
that way if its not assigned theres no errors... 
and you can still have debugs to log it to urself..
willow lodge
#

I have a question what does "return" do?

rich adder
#

it returns out of the function

rocky canyon
#
    {
        if (target == null)
        {
            Debug.LogWarning("No target assigned!", this);
            return; // exits Update() early
        }

        // If we got here, target exists — safe to run logic
        transform.LookAt(target);
        Debug.Log($"Tracking {target.name}");
    }```
#

^ chek the comments on that it'll make more sense

willow lodge
#

Thx

rocky canyon
#

its a simple way to optimize ur code..

#

without trying too hard..

wild peak
#

Generated codes are like free money falling from the sky. Since you get free money, you won’t work to gain experience.
This message is copyrighted by Rod. All rights reserved.

rocky canyon
#

if thing isn't there -> dont do anything else

wild peak
#

sorry i was just bored

rocky canyon
#

if thing is there -> go for it

willow lodge
rocky canyon
#

is what its called in this context

scarlet pasture
#

Hey, how can i add a force to my player with a Strong value but only for a few Meters?

#

i only know how to apply force but i dont know how to make it that he only goes a few meters

rocky canyon
#

store the position when u start the force.. (check distance until its too great) then stop

scarlet pasture
#

how can i check the distance?

rocky canyon
#

thisPosition - thatPosition;

#

or Vector3/Vector2.Distance

scarlet pasture
#

can i stop with vector.zero?

#

at the end?

rocky canyon
#
   Vector3 start = transform.position;
    body.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);

    while (Vector3.Distance(start, transform.position) < distance)
        yield return null;

    body.velocity = Vector3.zero;```
#

yes exactly ^

rocky canyon
#

once the distance check fails u set it back

#

that will need to be run in a coroutine in case u hadn't used those before

scarlet pasture
#

if i use that in a antoher Script i need a Corutine? and a while loop? right because i need to run this code more then one time?

rocky canyon
#

like cs public void FireImpulse(Vector3 dir, float meters) { StartCoroutine(ImpulseDistance(dir, meters)); }

using System.Collections;

private IEnumerator ImpulseDistance(Vector3 dir, float distance)
{
    Vector3 start = transform.position;
    body.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);

    while (Vector3.Distance(start, transform.position) < distance)
        yield return null;

    body.velocity = Vector3.zero;
}```
rocky canyon
willow lodge
#

I FOUND THE PROBLEM

rich adder
#

brother.. I been telling you the problem

rocky canyon
rich adder
#

ops the red should be circled above

scarlet pasture
#

can i say if scale is -1 he is looking left? and give the player a force to left?

willow lodge
rocky canyon
#

lol.. 🫰 darn

rich adder
#

Im not talking about that
i been said its the prefab without the assigned SO

#

Blue line = its not the same value as the original prefab

rocky canyon
rich adder
#

you're spawning new prefabs with SO not assigned

rocky canyon
#

positive 100 -> moving to the right
negative 100 <- moving to the left

#

or up/down or w/e

willow lodge
rich adder
rocky canyon
#

no need to really check the direction unless ur wanting to do something like change the graphics to correspond to the direction ur moving

#

then u can just use inputs...

rocky canyon
#

if input = D -> moving right (graphics facing right) + forceToApply
if input = A <- moving left (graphics facing left) - forceToApply

willow lodge
#

THE PROBLEM IS FIXED

#

Omg

#

Its actualy fixed

rocky canyon
#

Nav's the best 🤜 🤛

willow lodge
#

🥲

#

Thank you @rich adder

rocky canyon
#

now go tell ur AI bot how stupid it was.. and tell it to never ever screw you over like that again 😉

rich adder
willow lodge
rocky canyon
#

thtas a good thing to do 👍

#

u can use it as a study helper... giving u things to go and look up on ur own..

#

it isn't too bad at refactoring code either.. (once u write some nasty code urself)

#

u can have it help tidy it up.. (for the most part its decent at that)

willow lodge
#

Thx man yall are the best

#

🥲 🥲

rocky canyon
#

✅ use as tool
🚫 do not use as tutor

#

and u should be good 👍

willow lodge
#

now the boxes wont spawn inside each other🥲 🥲 🥲

rocky canyon
#

Next bite sized bite

rich adder
#

welcome to dev. Going from one problem to the next

rocky canyon
#

half the time bugs be hiding behind other bugs 😅

rich adder
#

programming, the act of putting bugs UnityChanThumbsUp

willow lodge
#

Alright imma go to sleep i need to go to school tomorrow so byee👋 👋

rocky canyon
#

hangon

scarlet pasture
#

but why VelocityChange?

#

i thought we need use Impulse=?

rocky canyon
#

Impulse is a one-time all at once force..

#

it wouldn't make sense to use it over distance..

#

unless you want a instant DASH that dampens to zero over time or something

#

which is a bit different

scarlet pasture
#
    {
        if (transform.localScale.x > 0f) //Rechts
        {
            isFacingLeft = false;
        }
        else //Lin,s
        {
            isFacingLeft = true;
        }

        StartCoroutine(ImpulseDistance(dir, meters));
    }

    private System.Collections.IEnumerator ImpulseDistance(Vector2 dir, float distance)
    {
        Vector3 start = transform.position;

        rb.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);

        while (Vector3.Distance(start, transform.position) < distance)
        yield return null;

        rb.linearVelocity = Vector3.zero;
    }```i did it like that
#

i need to chanfge it to Vector2 haah

rocky canyon
#

simple enough.. do that and see if its what ur going after..

scarlet pasture
#

simple? is that bad?

#

and i also get a error haah

rocky canyon
#

no i mean its simple enough to change to a vector2

scarlet pasture
#

ahhhh

#

yeah did

#

already

rocky canyon
#

use Vector2.Distance instead

#

whats the error?

scarlet pasture
#

i dont really know, i need to google it i dont understand the error

slender nymph
#

ForceMode is for 3d, perhaps there's another (similarly named) type you want to be using there instead? consider reading the documentation for that method to find out

scarlet pasture
#

okay i will try it

#

rb.AddForce(dir.normalized * impulseForce, ForceMode2D.Impulse);

#

but know i cant use => velocityChange? i saw that its the same like Impulse but just ignore the mass, can i just set the mass to zero and after the Attack back again to the saved value?

#

in 2d only Impulse and Explosion exist, i think impulse should be fine. i just add a high value and the distace check should set the player to zero

#

hmmm i also saw that i cant use Coroutine for Animation Event

#

i need to use it in the Code spezifical altought i didnt like that

faint stump
#

Any idea when i play the sound, it take a bit of time before the sound is being Played.
in the AudioSource, there is a clip, a .wav with Decompress on Load, PCM,

using PurrNet;
using UnityEngine;

...
[RequireComponent(typeof(SoundPlayer))]
public class ObjectInteractiveRat : NetworkBehaviour
{
...

    [ServerRpc]
    public void Activate()
    {
        if (isActivated) return;

        if (type != InteractionType.DepositSpot)
            isActivated.value = true;

        GetComponent<SoundPlayer>()?.PlaySound();
        ActivateInteraction(type);
    }



using UnityEngine;
using PurrNet;

[RequireComponent(typeof(AudioSource))]
public class SoundPlayer : NetworkBehaviour
{
    [ObserversRpc]
    public void PlaySound()
    {
        PlayLocalSound();
    }

    private void PlayLocalSound()
    {
        AudioSource audioSource = GetComponent<AudioSource>();
        if (audioSource.clip != null)
        {
            audioSource.pitch = Random.Range(0.97f, 1.03f);
            audioSource.PlayOneShot(audioSource.clip);
        }
    }
}```
rocky canyon
# scarlet pasture in 2d only Impulse and Explosion exist, i think impulse should be fine. i just a...

multiple ways you can go about it but I like controlling my Vectors completely myself and just setting the rigidbody's vel

  • check for input / start coroutine
            // Dash input
            if (Input.GetKeyDown(KeyCode.LeftShift) && !isDashing)
            {
                Vector3 dashDir = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z).normalized;
                if (dashDir.sqrMagnitude > 0.01f)
                    StartCoroutine(DashRoutine(dashDir, dashDistance));
            }```
- dashVelocity is its own Vector I can control completely.. so if there is a value it gets added into my over-all vector.. if i **zero** it out.. it doesn't affect my original vector
```cs
            vel += dashVelocity; // add dash velocity
            rb.linearVelocity = vel;```
- the coroutine's job is to cut it off or zero it out once a condition is true, either by distance, or by time, or w/e you chose
```cs
        private IEnumerator DashRoutine(Vector3 dir, float distance)
        {
            isDashing = true;                 // start dash
            Vector3 startPos = transform.position;
            dashVelocity = dir * dashForce;

            while (Vector3.Distance(startPos, transform.position) < distance)
                yield return new WaitForFixedUpdate();

            dashVelocity = Vector3.zero;      // stop dash
            isDashing = false;                // allow next dash
        }```
gusty wagon
#

Hello gays what Code c++

wild peak
rocky canyon
#

Code c++ is :C plus plus and is what engines like Unreal use to code with..

Code c# is: C sharp and is what Unity uses to code with..

gusty wagon
rocky canyon
#

say I have a persistent scene that holds my game's main camera + post-processing setup.
each game/level scene (Level1, Level2, etc.) needs its own post-processing volume with different looks.

I’ve been debating how to handle this most of the morning:
A) Keep one persistent volume and find/apply the correct scene’s volume profile on load.
B) Let each scene use its own volume component (engine handles it).
C) Have a central manager with a list of scene names + profiles and just swap on load.

which setup do you guys prefer?

#

(im also curious b/c this idea can apply to multiple things and would change the way i build from here on)

scarlet pasture
#

@rocky canyon are u are inid Dev=

rocky canyon
earnest oak
#

stop modding and start making games

#

step 1 : quit

zenith cypress
#

That topic is not allowed here

scarlet pasture
#

are u guys talking about me?

solar hill
#

yeah you arent allowed to thank people here

#

jk someone was talking about modding

#

wasnt you i think

scarlet pasture
#

i cant thank?

#

what is modding?

rich adder
scarlet pasture
#

ahhh

#

so they also dont talk about me?

rich adder
#

they are referring to the person who deleted their post

scarlet pasture
#

ah okay now i understand

tired python
scarlet pasture
tired python
#

I don't really know whether I would be of much help honestly

rocky canyon
scarlet pasture
#

we both can learn from each other

tired python
scarlet pasture
#

totall maybe 2 months

tired python
scarlet pasture
#

active time

tired python
scarlet pasture
scarlet pasture
tired python
#

will friend you for the time being. gonna ping once i complete atleast one game

scarlet pasture
#

okay, im waiting at u

#

just text me

#

if u are ready

mint imp
#

so wholesome

earnest oak
#

Where do i get people to playtest

#

Ima gts gn

slender nymph
#

!test-requests

radiant voidBOT
# slender nymph !test-requests

Asking for testers via DM is a suspicious activity. Please upload your game to a publishing platform and make a ⁠#1180170818983051344 post. Use Itch.io or Unity Play if you are unfamiliar.
⚠️ Users should use the utmost care when dealing with executables, compressed archives, or .apk files. A common scam involves fake games that seek login tokens or other private data, compromising accounts, and potentially bypassing two-factor authentication.

timid egret
#

CustomPropertyDrawer fails to call OnGUI in some cases

plucky copper
#

Is there a downside performance wise to using a GameObject [MonoBehaviour] based State Machine for relatively simple entities?

I ask this because the convenience of being able to use SetActive() to disable and enable GameObjects for such a state machine + the visual organization would be quite handy.

shell sorrel
#

perf should be fine

plucky copper
#

Its not like I'm going to have thousands of entities on the screen A and B: I do plan to disable entities entirely when they are off screen, and enable them when they are off screen anyways....

Cool, thanks!

shell sorrel
#

am not enabling and disabling them have custom editor logic to visualize but have state hierarchal state machines represented with game objects and some of hundreds of states and its running fine

#

it can be nice since it makes visualzing them easy, but also means your states can easily make scene references

dreamy scarab
#

how do i restore broken prefabs?

(before anything, i do have a github for backup, but i want to know if there is other options)

i was changing a flamethrower particle/light in my enemy prefab, then my whole pc goes brrrrrrr (frozen screen)... it shuted down and when i open unity again a lot of things on the scene (which as prefabs) had been corrupted.

how's the stardard way to solve it?

teal viper
dreamy scarab
#

ok ok

#

i had to try it

#

but tks

wintry quarry
#

Different people/projects do things differently. Note some projects use shared textures for multiple models making the latter infeasible

#

Also not a code question

sand dagger
languid pagoda
#

anyone got any idea how you do floating origin rebasing on a multiplayer game?

wintry quarry
#

but really it's complex, especially if there's physics involved

#

the server might have to run a physics sim for each "bubble" so to speak

shell sorrel
#

its already a fiddly soultion to a problem, but turns into a fiddly and very complex problem if he floating origins need to be networked as well

teal viper
#

That's why you don't really see many games with such features built on Unity. This is something you'd probably want a custom engine for.

#

Not just this, but in general, a game of such scale and complexity.

shell sorrel
#

also lot of game that need it work around it in other ways

#

like large universe for the player but PVP kinda happens in its own zones

languid pagoda
#

I guess the real solution here is to use ECS on the server side and implement my own shit using double

teal viper
#

It's not just the floating point issue. There are a lot more considerations.

languid pagoda
#

honestly if I had the time/skill I probably would have my a custom engine for this game

languid pagoda
teal viper
#

Point is big games require a lot of consideration, resources and human hours. Something that usually big companies have, not individuals. They can afford to develop an in-house engine for the task.

languid pagoda
#

So is what you''re suggesting its not possible in unity?

teal viper
#

No, definitely possible. But it might be more difficult or problematic in the long run(compared to an engine designed specifically foe the task).
And you mentioning ECS is a good point. It might make such problems easier to solve.
All I'm saying is "don't bite more than you can chew". (or I guess do it at your own risk)

languid pagoda
meager gust
#

Star Citizen does 64-bit floats so they don't have to do this... but their game also runs like a hunk of garbage, even with their endless millions of dollars in funding

#

Chunk borders (literal edge cases) would get weird if you've got players fighting on it, or physics happening across it. I used to be pretty interested in solving this problem until I realized how much work it would be.

#

I dont think real origin shifting (different from the chunking I described above) would work for multiplayer with proper rollback, because the server's origin would be different from the client's origin and you're probably going to run into strange determinism issues. Or maybe not. I dont know.

#

You said the server doesn't need to simulate anything, so that probably makes things 100x easier. You certainly don't need 64-bit floats or a custom game engine to do this.

hot wadi
#

Load the entire model at once just like Nintendo stonks

tender mirage
#

Is there an reason why multiple class child class isn't working at all?

public class PlayerScript : MonoBehaviour
{

    //Player movement class
    [System.Serializable]
    public class PlayerMovement : PlayerScript
    {
        //Components
        private Rigidbody2D playerRigid;

        //Player Properties
        [SerializeField] private bool IsMoving;


        [SerializeField] private float playerSpeedX = 0;
        [SerializeField] private float playerMaxSpeedX = 3.5f;
        private float playerVelocityX = 0;

        private void Awake()
        {
            //Get Components
            playerRigid = GetComponent<Rigidbody2D>();
        }


        private void FixedUpdate()
        {
            InputMovement();

        }


        private void InputMovement()
        {
            //Right left movement
            if (Keyboard.current.dKey.isPressed)
            {
                //Apply speed
                playerRigid.linearVelocityX = playerSpeedX;

                //Build speed
                playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, playerMaxSpeedX, ref playerVelocityX, 0.6f);


            }
            else if (Keyboard.current.aKey.isPressed)
            {
                //Apply speed
                playerRigid.linearVelocityX = playerSpeedX;

                //Build speed
                playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, -playerMaxSpeedX, ref playerVelocityX, 0.6f);



            }
            else
            {
                playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, 0, ref playerVelocityX, 1);
            }



            //Up down movement
            if (Keyboard.current.wKey.isPressed)
            {
                playerRigid.AddForce(new Vector2(0, 15));

            }
            else if (Keyboard.current.sKey.isPressed)
            {
                playerRigid.AddForce(new Vector2(0, -8));


            }

        }

    }
}
#

my player doesn't move anymore

#

after applying the sub class

#

Does fixed update not work inside of a subclass perhaps?

runic lance
tender mirage
runic lance
#

that said, this is a very strange way of organizing the classes, I would recommend against it

sour fulcrum
#

I’m pretty sure every monbehaviour definition needs its own monoscript file but i could be mistaken

tender mirage
#

Yeah, i've never touched on multiple classes before, but i wanna solve the problem of my code always turning out unorginized

#

can't i just have multiple classes in one larger script? that's how i would like to orginize my projects.

#

so PlayerScript > PlayerMovement, Stats, etc

runic lance
#

it's unlikely that you will solve any organization issues with nested classes
you can have namespaces though

sour fulcrum
tired python
#

which channel should I post on for unity related beginner problems?

tender mirage
sour fulcrum
#

no

#

you should have them in different files

runic lance
#

the class split is not bad, this is a good approach using composition
you just need to move them to different files

#

try researching a bit about OOP and composition, then you will most likely be able to organize the project better

tender mirage
#

I would love to have multiple classes in 1 script to be fair

#

But fair, in the inspector, i suppose seperating scripts and their components to configure them

#

would be alot cleaner

grand snow
#

Unity just does not support this for monobehaviours so dont

tender mirage
#

Used to mess around with javascripts. and the scripts i worked on were one large script with multiple classes

grand snow
#

suck it up and stop

tender mirage
#

sheesh i already did

runic lance
#

large files are usually a pain to work with, this is a better approach

sour fulcrum
#

Your safe now

grand snow
#

Its a bad idea in general because your source control management will take a shit

tender mirage
#

lmao

#

Well, i certainly wasn't expecting this.

#

Still, thanks for the advice

#

peep

grand snow
#

welcome to the real world ✨

tender mirage
#

Sure.

sour fulcrum
#

Imagine my toilet and shower instruction manual being printed in the same booklet because their both bathroom related

grand snow
#

so tempted to correct you there

sour fulcrum
#

To build it not use it!!

tender mirage
#

Yeah, no clue why the scripts i was messing around with were structured like that...

#

and then i ended up structuring my scripts like that myself, especially on lua, it got much worse.

#

thank god i was atleast using modules here and there but still..

grand snow
#

to be fair, languages like JS and lua let you do crazy things

#

but in strictly typed languages its a different story

polar dust
tender mirage
#

Yeah, i can see why now.

#

also multiple scripts in the inspector seems like a better approach anyways

grand snow
#

a component/class should try to do one job

tender mirage
#

rather then 1 large script component

tender mirage
grand snow
#

as you do more you learn what not to do
e.g. make one mega script and realise later you really need to re use something elsewhere

rugged beacon
#

managers scripts type shi

scarlet pasture
#

Hey

#

Can Sombody help me, i try to fix it since 1 hour, my Player Cant flip. I Event coded it and somthing isint working right. I Really dont know what: ``` public System.Collections.IEnumerator ANIM_LightAttack()
{
if (isDashing) yield break;
if (isCurrentlyAttacking) yield break;
if (playerMovement2DScriptRef == null) yield break;
isCurrentlyAttacking = true;

    playerMovement2DScriptRef.allowFlip = false;
    playerMovement2DScriptRef.allowDash = false;

    anim.SetTrigger(LightAttack);
    anim.SetBool(WalkParam, false);

    yield return new WaitUntil(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);
    yield return new WaitWhile(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);

    isCurrentlyAttacking = false;

    if (isCurrentlyAttacking == false) 
    {
        playerMovement2DScriptRef.allowDash = true;
        playerMovement2DScriptRef.allowFlip = true;
        Debug.Log("ich darf" + playerMovement2DScriptRef.allowFlip + ""); 
    }
}```
naive pawn
#

what do you mean by "can't flip"?

scarlet pasture
#

like i coded in my Player Script a Flip functionen with a bool. When bool is true he can look to left or right

#

in every other Animation it work but not in the Attack Animation

#

when i say allowFlip = false, rthe player dont react to the Inputs of the Player and he cant look to the right or left

naive pawn
#

so what's the issue?

#

is that not what you want?

scarlet pasture
#

the issue is after the Attack he should flip and look in both direction inpendet with the Inputs. but he is just frozze im his current loock diraction

#

he only can look to right as a example. even i cleraly said he is allow to look in both diractikon.

#

also the debug isint really fired. i dont fint the issue tbh

naive pawn
scarlet pasture
#

yeah i know, but i dont understand why

naive pawn
#

add logs further up - before the waitwhile, etc

scarlet pasture
#

did, it runn until it reach this line =>

#

yield return new WaitWhile(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);

earnest oak
#

when im making an animation in blender and export it in unity why is it in so many layers

scarlet pasture
#

altought the Animation ending, so it cant be the issue. i thought abut just set allowFlip = false in my Combat System.

#
    {
        state = AState.Startup; elapsed = 0f;
        lightHitbox.enabled = false;
        Vector2 dir = transform.localScale.x > 0 ? Vector2.right : Vector2.left; 
        if (anim != null) StartCoroutine(anim.ANIM_LightAttack());
    }

    void EnterActive()
    {
        state = AState.Active; elapsed = 0f;
        if (lightHitbox) lightHitbox.enabled = true;
        Debug.Log("Ich sollte angreifen!"); 
        Vector2 dir = transform.localScale.x > 0 ? Vector2.right : Vector2.left;
        FireImpulse(dir, lightLungeDistance, false);
    }


    void EnterRecovery()
    {
        state = AState.Recovery; elapsed = 0f;
        if (lightHitbox) lightHitbox.enabled = false;
    }

    void EnterCooldown()
    {
        state = AState.Cooldown; elapsed = 0f;
    }

    void EnterIdle()
    {
        state = AState.Idle; elapsed = 0f;
        inputBuffered = false;
        if (lightHitbox) lightHitbox.enabled = false;
    }```
#

i think i would be better in herer

#

so Chris do u know what the issue can be?

naive pawn
scarlet pasture
#

yeah...

#

i heard in the internet with Somthing about "try" and "finnaly"

#

never used that. i give it a try

naive pawn
#

log some more values then

scarlet pasture
#

okay!

naive pawn
#

specifically, the things you;re checking

scarlet pasture
#

i mean? is the Animation playing?, is the Animation ended?

#

i think this can help

naive pawn
#

also check if you're looking at the right animator

scarlet pasture
#

but i fixed it

#

i just put the allowFlip logic in Combat System. I think its either way better to handle that in Combat System instead of in Animation Handler

#

but i hope the Code block dont give me more problems in future haahah

scarlet pasture
tender onyx
#

Have a simple shooting script where the sphere will fire a cube from in front of it. For some reason, even though the sphere / firing point is rotated, the cube never changes on the y axis. The EXACT same script on my player can instaniate the same cube going wherever he's looking. Any ideas? Both scripts just use: Instantiate(fireball, transform.position, transform.rotation);

sour fulcrum
#

youd need to post code

naive pawn
#

!code

radiant voidBOT
naive pawn
#

please post it properly as the "large code blocks" section instructs

red igloo
rough granite
#

So each jump will just grow larger than the last even if it was a "tap" vs a "hold"

red igloo
#

It works now thanks for that

wide aspen
wide aspen
hot wadi
#

Tapping and holding is a bit hard to separate. I would rather track when the button is held down to apply the jump force, and then wait for the button release to apply a little downward force so it stops jumping higher. Either with AddForce or setting velocity. That’s my idea

red igloo
slate epoch
#

So, I have an extremely annoying problem that I've been trying to tackle for hours without success. The issue is: I'm trying to move a dynamic rigidbody 2d with linearVelocity. I can see that the velocity is changing if I Debug.Log it. However, the object remains perfectly still. I would guess that it's doing so because the animator that I'm using is setting its position and doesn't allow to change it via code, as if I disable the animator, the object DOES move. However, setting the transform directly or using MoveTowards still works for some reason. I think the reason is because in another, unrelated clip, I do set the position via the animation tab. How can I solve this? I've tried enabling and disabling the apply root motion but still nothing

wide aspen
slate epoch
hot wadi
#

Why are u setting the position with animation and code at the same time?

wide aspen
slate epoch
red igloo
wide aspen
slate epoch
#

ok I removed the property and put apply root motion to false and now it works. I'll just leave before I insult this god forsaken engine so much that I get banned from the server

hot wadi
wide aspen
# red igloo its being called in Update

probably best to leave that as is then. and just set the rb.velocity. Also I think you might want to move it to FixedUpdate() later on as setting forces in Update() can sometimes cause random issues with physics.

edgy sinew
red igloo
edgy sinew
#

Update and FixedUpdate are not in sync. Typically the way to accomplish this is to receive the input in Update, store it in a variable, and "consume" it in the next FixedUpdate.

red igloo
edgy sinew
scarlet pasture
scarlet pasture
red igloo
scarlet pasture
#

ahhhh

#

how long do u code?

#

first u need to check is the player currently pressing the button and not in the air

hot wadi
#

Technically the longer u hold the key, the higher u jump

edgy sinew
#

@red igloo

// Verbose example for extra learning & clarity.

bool jumpHeld = false;
public void jumpButtonPressed(InputAction.CallbackContext context) 
{
    if (context.started)
        jumpHeld = true;
    if (context.canceled)
        jumpHeld = false;
}

void Update() 
{
    
}

void AddInitialJumpImpulse() 
{
    rigidbody.AddForce(..., ForceMode.Impulse);
}

void AddAdditionalJump()
{
    rigidbody.AddForce(..., ForceMode.Force);
}

float maxJumpCanBeAdded = 10.0f;
float currentlyAdded = 0.0f;
void FixedUpdate() 
{
    if (jumpHeld && !characterIsJumping && jumpAvailable)
    {
        AddInitialJumpImpulse();
        currentlyAdded = 0.0f;
    }
    else if (jumpHeld && characterIsJumping && currentlyAdded < maxJumpCanBeAdded)
    {
        currentlyAdded += Time.deltaTime; // in FixedUpdate this is automatically fixedDeltaTime.
        AddAdditionalJump();
    }
}
edgy sinew
#

@red igloo let me know if that makes sense.
Note that This doesn't prevent "press jump button, let go, then press again and still add more force" stonks - you can handle that easily with an Enum I think.

#

Also I highly recommend trying ForceMode.VelocityChange (will require different scaling of force applied)

naive pawn
#

they aren't working in 2d

scarlet pasture
#

yeah they dont work

naive pawn
#

that's not what i said

#

the 2 people discussing above are working in 3d

scarlet pasture
#

what did u said? i dont understand u my bad

naive pawn
#

so they are using ForceMode, which has 4 modes

scarlet pasture
naive pawn
#

the 3d and 2d engines are actually different third-party engines, so they work differently, they provide different things, there are subtle inconsistencies between them, such as this

#

ForceMode (3d) has 4 modes - Force, Impulse, Acceleration, and VelocityChange
ForceMode2D has only 2, Force and Impulse

#

the explosion force you're thinking of is not a forcemode, it's a separate method altogether that exists in the 3d version

naive pawn
#

i... don't know how it's different from an impulse/velocitychange force though. i work in 2d

wintry quarry
#

(Also that method takes forcemodes itself as a parameter)

#

AddExplosionForce is basically just a convenience method for adding a force outwards from a central point with a distance falloff (direct inverse linear relationship) and an optional extra "upwards" modifier

naive pawn
#

oh... i've reinvented that...

red igloo
naive pawn
#

you do not need playerinput, no

#

you can use playerinput with these, but as the name suggests, this is just for a callback on the event

scarlet pasture
scarlet pasture
#

thank u

radiant voidBOT
naive pawn
scarlet pasture
#

sorry

willow lodge
#

Hey everyone, i have a dumb question:
When we reference the rigidbody in unity like
Public RigidBody2d rb;
Why do we have to get the component in void update()?
Didnt we already reference the component in the script?

wintry quarry
#

Note that:
public RigidBody2d rb; simply creates the variable

#

the actual part where you set up the reference needs to be done in the Unity editor in the inspector

#

if you didn't do that, then you just have a null variable, not a valid reference

willow lodge
#

Hmmm intresting

#

Thanks for the explaination

shell sorrel
#

its so you can click and drag in any object matching the type not just ones on the current GameObject

polar acorn
#

Don't do get component in update basically ever

willow lodge
#

Why?

#

Some ppl do it

polar acorn
#

You get it in start because of all the things Praetor said

polar acorn
#

Update runs every frame. GetComponent is slow. There is zero point in re-getting the same reference every frame

#

Do it in Start or Awake

willow lodge
#

Oooh ok

wintry quarry
# willow lodge Some ppl do it

you'd really have to show the particular individual circumstances you're talking about. Different situations call for different things.
There are also inefficient and wasteful ways to do things which people absolutely do, usually from a lack of understanding

willow lodge
#

Nice

#

Damn i love game dev

hot wadi
#

This is why u double check everything

tender mirage
#

I always get a null reference whenever i try to grab the script from a another object and output a text variable

TMPro;
using UnityEngine;
using UnityEngine.UI;

public class PlayerDebug : MonoBehaviour
{
    //Components
    [SerializeField] private GameObject playerVelocityObject;

    private TextMeshPro playerVelocityText;


    //Scripts
    [SerializeField] private PlayerMovement playerMovement;

    private void Awake()
    {
        //Get Components
        playerVelocityText = playerVelocityObject.GetComponent<TextMeshPro>();


    }

    private void Start()
    {
        UpdateText();
    }

    private void UpdateText()
    {
        
        playerVelocityText.text = "VelocityX: " + playerMovement.playerRigid.linearVelocityX + "\n" +
                                  "VelocityY: " + playerMovement.playerRigid.linearVelocityY;
        
    }
   
}


using NUnit.Framework;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.InputSystem;
using TMPro;

public class PlayerMovement : MonoBehaviour
{
    //Components
    public Rigidbody2D playerRigid;


    //Player horizontal movement
    [SerializeField] private bool IsMoving;

    [SerializeField] private float playerSpeedX = 0;
    [SerializeField] private float playerMaxSpeedX = 3.5f;

    private float playerVelocityX = 0;


    //Scripts
    [SerializeField] private PlayerSprite playerSprite;

    private void Awake()
    {
        //Get Components
        playerRigid = GetComponent<Rigidbody2D>();
    }
    //.........
keen dew
#

In the second one, why don't you just drag the reference instead of using GetComponent

#

In the first one, the component is probably TMP_Text instead of TextMeshPro. But you could make that one serialized as well instead of using GetComponent

tender mirage
#

True, although it is TextMeshPro, i've just been having this trouble with multiple projects with this reference error and it even became a nightmare of a mess lol

cosmic quail
scarlet pasture
tired python
#

can someone tell me what this means?

scarlet pasture
#

just drag it in the inspektor and build a fallback

cosmic quail
tender mirage
willow lodge
#

Hey everyone, how can i tell my script to replace the box prefab with another prefab? For example i want to replace the box with a rocket

scarlet pasture
#

no unity saves the reference. i would save some small micro perdomance

scarlet pasture
rich adder
#

they probably mean through script

willow lodge
scarlet pasture
shell sorrel
#

just make a other field for rockets and at runtime choose which one to use

rich adder
scarlet pasture
willow lodge
#

No worries

willow lodge
scarlet pasture
willow lodge
scarlet pasture
#

u could make a new field?

shell sorrel
scarlet pasture
#

in the inspekor drag the prefab in and use it

rich adder
#

if you're gonna have more than 2-3 items then its probably best to put them inside an SO

willow lodge
#

Do i REALLY have to make a new field?

scarlet pasture
#

i mean it would be simple

tired python
# rich adder What do you want to know ?

i want to know what it means. I have encountered problems before and i thought i understood what it meant but later found out that i understood it wrong. if you could tell me what it means, that would be helpful

scarlet pasture
#

why not?

rich adder
shell sorrel
rancid cloak
rich adder
shell sorrel
#

so that could be multiple fields or make it a array and keep a index of the current one

willow lodge
scarlet pasture
#

u can us OS

willow lodge
#

array?

scarlet pasture
#

or headers also a simple way for organisation in the code

#

for the Inpekor also

cosmic quail
rich adder
#

array could work but you have to know which index will be what object

willow lodge
#

I'll just go with the simple way

scarlet pasture
#

i mean u can search it per runtime, i just heard that it saves a "micro" small performace when u drag it inm the Editor

cosmic quail
shell sorrel
scarlet pasture
#

but it would make sense

shell sorrel
#

would just keep it simple with multiple fields or a array and a index

rich adder
tired python
# rich adder Sure but helps if you describe, which part are you confused about ?

so i understand that there is a vehicle class and a navigator class. the vehicle class has defined functions such as goforward and reverse and etc and navigator calls those functions using a function called move which takes in a class vehicle as its argument. problem is that if i try to implement a class train, why does it give an error?

willow lodge
rich adder
cosmic quail
shell sorrel
scarlet pasture
tired python
tired python
#

then what do you mean by derived class or is it a synonym for inheriting class?

naive pawn
#

several people have stated this, and it's really straightforward if you think about it

scarlet pasture
rich adder
naive pawn
#

GetComponent does the searching at runtime, a serialized reference does the searching at devtime
using the reference is O(1) with the id anyways (most likely)

cosmic quail
naive pawn
#

do getcomponent, but in Reset instead of Awake

shell sorrel
#

it really does not matter if you are doing a few one time lookups on Awake i just use what is more convenient

#

also i often just make my OnValidate setup the ref for me if its empty

#

that way its automatic or i can drag something in

rich adder
shell sorrel
#

worry about making the game

cosmic quail
naive pawn
shell sorrel
#

not little details like this

scarlet pasture
naive pawn
#

you don't do it in Awake and you do it in Reset instead. that's what instead means

scarlet pasture
#

is reset a function in Unity?

#

or do i need to code it my self?

naive pawn
#

it's a unity message yeah

scarlet pasture
#

ahhhhh didnt know that

#

when does "Reset" runed?

#

if the Gameobject is active?

shell sorrel
#

it gets called when the componet is created or when you run reset from its context menu

#

its only editor time

naive pawn
scarlet pasture
#

created? per runtime?

rich adder
#

@tired python
bad example violating LSP ❌

class Bird { public virtual void Fly() {} }
class Penguin : Bird { public override void Fly() => throw new NotSupportedException(); }```

good example for LSP ✅ 
```cs
abstract class Bird { public abstract void Eat(); }
abstract class FlyingBird : Bird { public abstract void Fly(); }

class Sparrow : FlyingBird { public override void Eat(){} public override void Fly(){} }
class Penguin : Bird { public override void Eat(){} public void Swim(){} }
tired python
naive pawn
scarlet pasture
#

yeah i understanded know

#

thanks!

cosmic quail
scarlet pasture
#

i really learn allot in this dc

languid pagoda
# meager gust Chunk borders (literal edge cases) would get weird if you've got players fightin...

Awesome thank you for the info. What I wound up deciding was since I'm just using the server to relay info to other clients and am not using the authoritive server model that networked entities do not need to be game objects. I am just going to do floating point shift on client and send their reap position as a double to the server and on the server network entities will just be a struct which contains doubles for the position

tired python
naive pawn
#
void Main() {
  Penguin penguin = new Penguin();
  MakeFly(penguin);
}

void MakeFly(Bird bird) {
  bird.Fly();
}
tired python
naive pawn
#

what is the error you're thinking of here

tired python
naive pawn
#

that's what override is for

tired python
#

oh

naive pawn
tired python
#

overrid prioritises a specific function i guess?

naive pawn
#

not really

#

go read the guide

rich adder
#

even though multiple classes have Eat(), each overrides the base abstract method.

the compiler checks the method exists (Bird.Eat()).
at runtime, C# calls the correct version based on the actual object type (Sparrow or Penguin)

cosmic quail
naive pawn
#

you would not want to globally reset

#

that would remove all your other configured values

#

this is probably something you'd need to have foresight with

tired python
#

how do i see an output on vs when i am using console to print stuff?

hexed terrace
#

just use the console in unity

tired python
#

tell me both then

rich adder
#

Debug.Log

tired python
#

ya but like where does it show?

polar acorn
#

The debug log

rich adder
#

in the Unity console tab / window

tired python
#

in...vs

polar acorn
#

!learn

radiant voidBOT
rich adder
#

no it doesn't show in VS

polar acorn
#

Debug Log should literally be the first line of Unity code you ever wrote

tired python
#

rly?

#

vs doesn't show an output?

polar acorn
rich adder
#

If you had a console app sure it makes a Console.Writeline output in a new terminal window but in Unity is just easier to use Debug.Log

tired python
naive pawn
#

did you import unityengine

polar acorn
tired python
#
class BaseClass
{
    public void Method1()
    {
        Debug.Log("Base - Method1");
    }
}

class DerivedClass : BaseClass
{
    public void Method2()
    {
        Debug.Log("Derived - Method2");
    }
}

class Program
{
    static void Main(string[] args)
    {
        BaseClass bc = new BaseClass();
        DerivedClass dc = new DerivedClass();
        BaseClass bcdc = new DerivedClass();

        bc.Method1();
        dc.Method1();
        dc.Method2();
        bcdc.Method1();
    }
    // Output:  
    // Base - Method1  
    // Base - Method1  
    // Derived - Method2  
    // Base - Method1  
}```
this is the code i am trying to upload
radiant voidBOT
polar acorn
#

And no, you don't

naive pawn
#

why not just use like, C# online for that

polar acorn
#

So how would you expect to use any Unity functions

naive pawn
polar acorn
#

Also main isn't going to work in Unity

rich adder
#

dotnetfiddle

polar acorn
#

Well, you can make a main function but you'd need to call it like any other function

naive pawn
#

you can google any well known language plus the word "online" and get an online runner/interpreter/compiler/etc

rich adder
tired python
#

it's not like cpp at all

naive pawn
#

it is

polar acorn
naive pawn
#

just that the context of unity isn't like individual executables

tired python
#

where's main where's cout

rich adder
uncut tide
#

I’m developing a 2D mobile game in Unity (URP)
I’m currently trying to make my Jelly objects feel more realistic and “gelatinous”, both visually and physically — soft, bouncy, and satisfying to watch — while keeping performance stable on mobile some advice

polar acorn
naive pawn
polar acorn
uncut tide
#

on unity ?

rich adder
#

make a bunch of points, connect said points. Now you got a softbody (obv there is more to that)

tired python
rich adder
uncut tide
#

thank you

naive pawn
tired python
#

oh

uncut tide
#

is there asset to use ??

rich adder
#

probably?

naive pawn
#

perhaps look up some c# tutorials if you want to explore c# on its own
there are some pinned in this channel
@tired python

rich adder
#

yes also more general question there is :

#

!cs

radiant voidBOT
tired python
#

ah it's working

#

so System is a header file?

rich adder
#

its a namespace

#

there is no header files

tired python
#

in c#?

rich adder
#

you can make a namespace anywhere

tired python
#

then what do you do if you wanna add more functions in general?

rich adder
uncut tide
#

I thought soft work just for 3d Am a beginner don't mind if I ask some simple thinks

rich adder
naive pawn
#

types exist inside namespaces - the global namespace, if none is specified.

uncut tide
#

yes I see a video I find a asset in unity library but he make my programme crash so I decide to makeit myself so why am here

tired python
#

just a recap, vs does not run code

#

vscode runs code

naive pawn
#

IDEs do not run code

#

they may integrate things that actually run code - interpreters or compilers+executables

tired python
#

i mean yeah, but if you do connect it to compilers, they do

naive pawn
#

but it isn't doing the execution itself

naive pawn
tired python
#

so vs can do that right?

naive pawn
#

sure, but not with a unity project

tired python
#

only for c#?

#

i mean like only if i installed c# while installing it...

naive pawn
#

unity has a specific context in which it runs

#

c# can run just fine. other languages can run just fine

tired python
#

aight i understand

naive pawn
#

other systems/contexts that expose that context can run too

#

unity does not, so it can't be run separately

tired python
#

i do remember getting the .net framework along with c# installed while downloading this vs. how do i use it then? because the way it is rn, my vs is basically acting like a notepad...it can't run stuff or even if it does, i don't really know abt it cus it's not outputting smth somewhere

naive pawn
#

!vs

radiant voidBOT
# naive pawn !vs
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

naive pawn
#

sounds like it might not be configured ^

#

though.. i don't remember these steps for vs. you sure it isn't vscode?

rich adder
#

You can test all the same stuff in unity using Debug.Log

you can use Start or Awake as the entry point

tired python
#

i had vscode before i formatted. a dev told me that if i wanna try modding, i might wanna use vs. i formated my pc and rn i only have vs installed. i do have mingw and python installed on my other drives

tired python
rich adder
tired python
#

so i should only be asking stuff here if my code requires using unity?

rich adder
#

Ask questions and discuss anything related to beginner coding concepts in Unity

#

if you want to talk general / basic & c# apps you should do it in the C# server I linked

tired python
#

oh i did not see that prolly sry my mistake

#

could you share the link again? can't seem to find it in your msglog

rich adder
#

!cs

radiant voidBOT
tired python
tired python
#

how so?

#

dm me

rich adder
#

uses c# to communicate with its C++ backend

#

its an engine, so it already has its own implenetations of Physics etc.

#

Arduino is a microcontroller that runs on C / Cpp code

#

Software vs Hardware, unity is not hardware

naive pawn
#

i mean.. honestly, i wouldn't say it's that much off

polar acorn
#

I'm just not sure what sort of useful insight is to be gained off of comparing the two

rich adder
#

Arduino just simplifies not having to buy a Devboard for programming a chip

naive pawn
#

c#/cpp are languages, unity/arduino are specific contexts that use said language with a specific library and specific constraints to interface with a system

the specific context/library/constraints/system part are vastly different, as described above, though

queen knoll
#

Yo

#

Any good vid to learn

naive pawn
#

!learn

radiant voidBOT
naive pawn
#

plenty there, and plenty on youtube

queen knoll
#

Ah

#

Thx

#

!learn

radiant voidBOT
rich adder
#

oh boy..

naive pawn
#

what did you think that would do

polar acorn
scarlet pasture
#

Hey guys can sombody give me a recomendation about how to hit only one time a enemy and allowing 2 enemys getting hit with one Swing?. i dont know how to approuch this?, i tridy it but every time it gets messy and dont really clean also really dont working. im currently try to improve my skills => ```cs using UnityEngine;
using System.Collections.Generic;

[RequireComponent(typeof(Collider2D))]
public class DoDamage : MonoBehaviour
{
[Header("References")]
[SerializeField] private CombatSystem combatSystemScriptRef;
[SerializeField] private Collider2D LightAttackTrigger;

[Header("Light Attack Settings")]
[SerializeField] private bool allowDamageApply = true; 
[SerializeField] private float baseDamage = 100f;
[SerializeField] private float LightAttackDamage = 10f; 
[SerializeField] private float HeavyAttackDamage = 30f; 

void Awake()
{
    if (LightAttackTrigger == null) LightAttackTrigger = this.GetComponent<Collider2D>();
    if (combatSystemScriptRef == null) combatSystemScriptRef = this.GetComponentInParent<CombatSystem>(); 
}

private void OnTriggerEnter2D(Collider2D other)
{
    if (!allowDamageApply) return;
    SetDamage(); 
    if (other.gameObject.CompareTag("Enemy"))
    {
        Debug.Log("der aktuelle Schaden ist" + baseDamage + ""); 
        var enemyHealth = other.gameObject.GetComponent<BaseEnemyHealth>();
        enemyHealth.TakeDamage(baseDamage);
    }
}

private void SetDamage()
{
    baseDamage = (combatSystemScriptRef.currentAttackMode == CombatSystem.AMode.Light) ? LightAttackDamage : HeavyAttackDamage; 
}

}

tired python
naive pawn
tired python
#

what's the harm in knowing though

naive pawn
#

(which is why genai is such a pain to deal with in educational contexts. it always has an answer, even if it's completely wrong)

naive pawn
rich adder
mint flicker
#

hey i need to make it so that my player can pass through the enemy but they all get stuck on each other as its like brick wall i just like it to pass through the enemy this should be simple but i cant find a tut on it

#

like in silk song you can pass throuth the enemy

#

its 2D

scarlet pasture
#

i think u can use matix collision?

mint flicker
#

ive heard of it but what boxex do i uncheck

scarlet pasture
#

i mean if u would disable the colliders of the enemy they would fall out of the map?

mint flicker
#

yeah

rich adder
mint flicker
rich adder
#

so uncheck the two layers you dont want to collide

mint flicker
#

ohh

scarlet pasture
#

so they dont effect each other

mint flicker
#

in matrix right

scarlet pasture
#

i dont really know im also new

rich adder
mint flicker
#

i will try

rich adder
#

there is also Physics2D.IgnoreCollision and Physics2D.IgnoreLayerCollision for run time
the former needing a reference to colliders you want

scarlet pasture
#

nav? can u help me with code i posted befor?

rich adder
#

use pastelink site

scarlet pasture
#

okay wait

#

!Code

radiant voidBOT
scarlet pasture
#

this is the code? can u tell me how to build this modular? i want to hit multiple Enemys at ounche but only one time per enemy for a small duraction..

mint flicker
#

wich box this is confusing

scarlet pasture
#

DAYUMN

#

this looks so sickj

scarlet pasture
#

but thank u!!

mint flicker
#

do i just test each one with player and enemy

frail hawk
#

just have a collection where you store the enemies, if the collection doesnt contain the enemy then do something

rich adder
scarlet pasture
wide aspen
scarlet pasture
frail hawk
#

i was actually referring to Bad_GameDev

scarlet pasture
#

to me ?#

#

AHHH Ha collection... i understand but i need to look about the syntax

#

i thought u mean Swetpig hahaha

rich adder
#

you ever use a List ?

#

its the same exact thing

#

except you cannot store duplicate items

#

myList.Add () etc

#

HashSet<Enemy>() enemiesHit = new()

#

Overlap or something like that
foreach enemy in enemies
if( enemies.contains(enemy)) continue // skip

scarlet pasture
#

[SerializeField] private List<Collider2D> colliders;

#

i only use somthing like that?

mint flicker
#

it wont detect the enemys damage if i seperate there layers

solar hill
#

isnt there an ignorecollision method

#

or something for 2d

rich adder
rich adder
#

but normally I make a sepearate Layer for Damages

wide aspen
#

you might have to add a childobject to both the player and enemy that has just a box collider as a trigger.

rich adder
#

this way i can separate solid body from trigger damages

rich adder
# mint flicker yes

I would make a seperate layer for trigger damage so you can seeperate the two

mint flicker
#

is that easy

rich adder
#

easiest way i can think of right now lol

#

this way you can use the Damage trigger layer for other hurtzones

mint flicker
#

is there a tut on it

scarlet pasture
#

yeah i saw a good one on yotube

mint flicker
#

ohh

rich adder
#

idk a specific tutorial, its easy though

#

put a trigger on the enemy, then use OnTriggerEnter to damage player
(the have to be on sepearate gameobjects and let the player detect the trigger)

scarlet pasture
rich adder
#

Iirc you can also keep colliders on the same gameobject and use the features on the Colliders but I havent used those much

scarlet pasture
rich adder
#

one for trigger and one for solid

mint flicker
scarlet pasture
#

it loooooks so nice!!

#

wow

mint flicker
#

on my twitter it shows the jump

#

look

scarlet pasture
#

i dont have one

#

can i still watch it?

mint flicker
#

can i share links

#

here

scarlet pasture
#

give it me personal via dm

mint flicker
#

okay

naive pawn
#

we would rather you not go to DMs

scarlet pasture
naive pawn
#

ah whoops thought yall were talking about a video about an issue

#

did not backread far enough

scarlet pasture
#

haha

#

i got scared for a moment

#

i dont knwo why aha

naive pawn
#

yeah for issues we'd rather you keep it here because that's kinda the point of a community server - to have multiple people available to check or help or proofread other answers

scarlet pasture
#

we talking about a twitter link

solar hill
#

otherwise the links have to directly be something related to an issue or a question you might have

mint flicker
#

ohh okay

pearl current
#

Hello, can anyone help me with my current issue in my 2d unity game. The main problem I'm running into is setting up invisible barriers to make it so that the player can't escape the games boundaries. Here's the setup:

  • Player game objects Rigidbody 2d set to kinematic and a box collider with set trigger = false
  • Wall game objects having a static rigidbody 2d + box collider with the same set trigger value.

The player can still walk straight through them and I have no idea how to fix it. Here are some screenshots as well as some code for context:

#
private void HandleInput()
{
    if (!isDashing && canMove)
    {
        moveInput = Vector2.zero;

        if (Input.GetKey(KeyCode.W)) moveInput.y += 1;
        if (Input.GetKey(KeyCode.S)) moveInput.y -= 1;
        if (Input.GetKey(KeyCode.D))
        {
            moveInput.x += 1;
            spriteRenderer.flipX = false;
        }
        if (Input.GetKey(KeyCode.A))
        {
            moveInput.x -= 1;
            spriteRenderer.flipX = true;
        }

        if (moveInput != Vector2.zero)
        {
            moveDirection = moveInput.normalized;
            lastMoveDirection = moveDirection;

            
            float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
            Aim.transform.rotation = Quaternion.Euler(0, 0, angle);
        }
        else
        {
            moveDirection = Vector2.zero;
        }

        
        if (Input.GetKeyDown(KeyCode.LeftShift) && dashCooldownTimer <= 0f)
        {
            StartDash();
        }
    }
    else if (!canMove)
    {
       
        moveDirection = Vector2.zero;
    }
}

public void HandleMovement()
{
    if (!isDashing && canMove)
    {
        
        if (moveDirection != Vector2.zero)
        {
            Vector2 targetPosition = rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime;
            rb.MovePosition(targetPosition);
            animator.SetBool("isMoving", true);
        }
        else
        {
            
            animator.SetBool("isMoving", false);
        }
    }
    else if (isDashing)
    {
        
        Vector2 dashVector = lastMoveDirection;

        
        Vector2 dashDisplacement = lastMoveDirection * dashSpeed * Time.fixedDeltaTime;

       
        rb.MovePosition(rb.position + dashDisplacement);

        dashTimeRemaining -= Time.fixedDeltaTime; 

        if (dashTimeRemaining <= 0f)
        {
            StopDash();
        }
    }
}```
wide aspen
rich adder
pearl current
pearl current
rich adder
pearl current
#

should I still use .velocity, i've seen that it's been depricated

rich adder
pearl current
#

VS code tells me to use .linearVelocity

#

yeah

#

ty!

rich adder
# pearl current VS code tells me to use .linearVelocity

if you're ever curious how the other suggestions i made works, check out a good example here (timestamped)
https://youtu.be/7iYWpzL9GkM?t=2202

Guide on many of the first steps building up a top down 2d pixel art RPG from scratch in Unity 2022 version. The goal of this crash course is to cover as many relevant beginners topics as we can but linked together in actually building out some prototype mechanics for a potential game.

For the video, I'm using this mystic woods pack for this tu...

▶ Play video
pearl current
#

Should I try using transform.Translate instead?

rich adder
rich adder
pearl current
#

the only one that's set to kinematic is the player

#

should the player be dynamic?

#

ahh

#

yes he should

rich adder
#

yes. If you use kinematic then you'd use MovePosition with the rb.Cast like the example in the video

pearl current
#

ahh gotcha

#

perfect, thank you!

rain solar
#

is there such thing as a reduction algorithm that can make those big flat faces into 2 triangles intead of a ton of triangles?

shell sorrel
#

well in the case of a cube like this, a convex hull would do it or even getting its bounding box and making a mesh from it. but aside from that most 3d packages do have mesh decimation tools

solar hill
#

i feel like a simple quad remesh in blender could cut this down into 16ish quads.

sand dagger
#

How do I add a range to a list? I'm trying to make a dice system with lists just out of curiosity, but it seems like I'm going to have to do

_numbers.Add(1);
_numbers.Add(2);
_numbers.Add(3);
_numbers.Add(4);```

So on and so forth until I get to 20, which is fine tbh, but is there any way to make it more efficient and just create a list from 1 to 20 without 20 lines?
rain solar
sand dagger
keen dew
#

Depends what you mean by "efficiency"

sand dagger
#

In this case, able to write _numbers.Add(x-y); instead of writing _numbers.Add(x) for every single number

#

Or however the code works

#

Condensing however many lines into just one or two maybe

keen dew
#

There is no built in method for specifically that, no

#

The for loop would be two lines

rich adder
naive pawn
#

"range" in a collection just means multiple consecutive elements

runic lance
#

you could also get fancy with enumerables

myList.AddRange(Enumerable.Range(1,20))
rich adder
#

LINQ 🥵

#

If I'm not mistaken for loop is usually faster

sand dagger
rich adder
sand dagger
#

Like if I had a D20 but I want it to have a higher chance of landing on D16-D18

rich adder
#

use whatever works for your usecase, the difference are marginal

runic lance
#

the way I suggested is just a shortcut for a for loop, in any case
it just looks a bit nicer

rich adder
#

ya looks clearner but they both pretty much do the same thing loll

runic lance
#

and probably a bit slower, but irrelevant in this case

sand dagger
#

Yeah this is being used for just a number generator, so speed isn't a concern

rich adder
#

or join

runic lance
#

also

Debug.Log(string.Join(',', myList));
sand dagger
#

Not just one number

rich adder
#

you need an index of it to print a number

#

_numbers[0] prints first one . etc.

sand dagger
#

Just so y'all can see exactly what I've got

rich adder
#

and which one you wanna print ?

#

use Join if you want a single line printed

sand dagger
#

I want to print one of them at random

#

Again this for a dice system

rich adder
#

Debug.Log(_numbers[Random.Range(0, _numbers.Count)]);

sand dagger
#

So if I were to start it again, I'd get a different one

#

Length has a red line under it

rich adder
#

basic c# stuff
var randomIndex = Random.Range(0, _numbers.Count)
var randomNumber = _numbers[randomIndex]

#

sorry lists use Count

#

arrays use Length cause they're fixed.

sand dagger
#

Okay so, something weird, I'm getting random numbers now which is good, but 14 random numbers instead of just 1

rich adder
#

you put it in the loop or something

sand dagger
rich adder
#

yea u are doing that as many times as numbers in your numbers list

#

put it out of the foreach if you dont want to do it as many times

scarlet pasture
#

what is this?

#

i seend this the first time

rich adder
scarlet pasture
#

to what?

#

to _numbers?

rich adder
#

ah beat me to it ^