#💻┃code-beginner

1 messages · Page 755 of 1

naive pawn
#

there are cases where magic strings can't be easily avoided, usually when interacting with external systems like shaders. but unity object references is not one of those cases

#

there is a built-in method to get objects by name, Find, but for the reasons mentioned above, you generally shouldn't use it, and in 99.999% of cases you won't need to anyways.

scarlet pasture
#

okay, so u all never build a fallback in awake?. i also never really saw that in a tutorial, i dont really know why and from where i got this hahah

#

but okay, atp i use SerializeField

#

Thanks for the Explanation.

sour fulcrum
#

As mentioned previously fallbacks in general aren’t really a thing no

#

Only when valid results are out of your control i suppose (eg. Network related)

keen dew
#

Fallbacks are used for things that have a reasonable chance of failing, for example network requests or connecting to a gamepad or something like that. But things like assigning component references either always work or never work, so there's no point in making a secondary mechanism for it

umbral bough
#

bump

naive pawn
teal viper
#

You might need to cache the input in an update loop. It's not clear where OnScenrGUI is called and whether inputs are valid at that point of frame.

scarlet pasture
teal viper
scarlet pasture
naive pawn
umbral bough
naive pawn
#

Used in EventType.MouseDown and EventType.MouseUp events.
from Event.button

so yeah that just.. doesn't work

teal viper
umbral bough
naive pawn
#

scrolling and clicking are just, separate events

#

you don't get the full status of the mouse as part of the event

#

you need to store that separately

naive pawn
umbral bough
#

I see, so you would suggest running the update loop and checking whether certain buttons are pressed?
If yes, should I use the old input manager or what?
Iirc that's deprecated, but idk what else to do since this is a really small asset you are supposed to just import into the project and it works.

naive pawn
#

not sure where you got that suggestion from

naive pawn
#

im not the same person as dlich

zinc totem
#

I have a question, How do you implement jump mechanics in 2D top-down?

umbral bough
#

well yes, but it happened during the same conversation and that's all the info I have, I am fully open to other suggestions

naive pawn
#

you could not have them, you could have gaps, you could have a 3d dimension, you could utilize faking height with a Y offset, or multiple of the above

naive pawn
#

the scroll and the hold will not come at the same time

#

(not sure why you did button == 0 anyways though.. that's left click)

naive pawn
teal viper
umbral bough
naive pawn
#

yes, the standard is 0 = left click, 1 = right click, 2 = middle click

umbral bough
teal viper
#

Ah, I guess it could just be a logic error then.

#

I'd confirm what Chris is saying first.

#

And if not, then documentation is the place to start.

umbral bough
#

it just stays at 0 when I lmb

naive pawn
#

nope

#

as the documentation says, it's used for mouseup/mousedown events, not scrollwheel
it was probably just 0-initialized

naive pawn
teal viper
#

Actually, looking again at the code, I stand by what I said.

umbral bough
naive pawn
#

there probably isn't

#

again - they are separate events

teal viper
#

The issue is that they're not in any input callback, but in on scene gui. So whatever happens to be the current event at that time is returned.

umbral bough
teal viper
#

What's Event? I thought it was unity api, but I don't see it in the docs...

naive pawn
#

you just need to store the state separately, like i said initiallyjs OnSceneGUI() { var e = Event.current; if (e.type == EventType.ScrollWheel && e.modifiers == EventModifiers.None) { if (rightClickHeld) { ChangeSpeed(e.delta.y); } else { Zoom(e.delta.y); } e.Use(); } } it would have to be something like this, and then keep the rightClickHeld state according to events you receive of type MouseDown and MouseUp (potentially also in this callback)
(also probably with better names, like whatever rightclicking is supposed to do)

can't confirm this would actually work, due to the event processing stuff dlich mentioned, though.

umbral bough
naive pawn
#

oh my god this bullshit again

#

at least read the damn docs of whatever you're using

teal viper
umbral bough
#

ok, well thanks for the help

teal viper
#

So yeah, Chris is right.

#

Read the docs page.

#

And then your code again.

#

Note how the docs mention a different callback too.

#

Not the on scene gui

umbral bough
arctic scarab
#

Hi, I'm currently a uni student, recently got into unity and our assigment is to create a game. I need help explaining the coding logic behind AI detection + chase + patrol, we're making a stealth game with zombies, but it seems it's going to be overly complicated with the AI for people who just began using unity

#

We got around 9 weeks and it would be amazing if someone taught me some basics

slender nymph
#

!learn

radiant voidBOT
arctic scarab
#

ah, that helps as well, thanks man

real thunder
#

What would be the a good way to sync animations and AI if an enemy being a MonoBehaviour FSM in Update?
Last time I used to make use of StateMachineBehaviour scripts on states toggling different variables in the animator
but that's just disgusting and I have to make a new var/script for each state

#

main issue is figuring out a moment when the animation ended

teal viper
#

animation events

real thunder
#
public class StateMobAttack : StateMachineBehaviour
{
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        animator.SetBool("IsAttackingEnded", false);
    }
    override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        animator.SetBool("IsAttackingEnded", true);
    }
}

this script of mine makes me very sad

empty onyx
regal aspen
#

hello is there anyone i can ask for help with some code? i'm doing a 2D space shooter for a course and i've run into some walls i can't really wrap my head around. i asked the instructor for some advice and he gave me a non-answer. i understand he can't just give the answer but i'm stupid (to put it bluntly) and need the direction

real thunder
#

I can pinpoint my exact issue where a mob is in an "attacking" state and a player is far away
I want it to stop attacking and go chasing the moment animation of an attack finished
And so far it's the best callback I figured I can get

radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

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

-# For more posting guidelines, go to #🌱┃start-here

naive pawn
real thunder
#

mecanim just makes me sad, tell me if you know better solution to the problem I mentioned

#

there are events but they have edgecases with blending and don't look good for game logic

regal aspen
#

sorry. i'm trying to set up a laser weapon using the Raycast function and to have it bounce off of a wall using the standard collision we were shown "if (collision = ect)" but when i use the input for the object's layer "gameObject.layer = 6" it gets upset and spits out an error

scarlet pasture
real thunder
#

yes

scarlet pasture
# real thunder yes

im really not the best, u can use either a Animation Event via code that say "Im Done" or u only use Code like i thid

#

i can send u a exapmple code

#

the Script automaticly detects if the Animation is done

fickle plume
#

Other than that you should post the code with the question.

#

!code

radiant voidBOT
regal aspen
arctic scarab
real thunder
arctic scarab
#

our project is too ambitious for the time we got haha

scarlet pasture
real thunder
#

it feels like a crutch that's what I mean

arctic scarab
#

also, there is this thing with Input Action manager and another way to do movement without it, which is better for a beginner?

rich adder
#

!code

radiant voidBOT
regal aspen
#

trying to fix it my bad

rich adder
#

what is going on here if(collision = (gameObject.layer == 6))

scarlet pasture
#

@BlackHunter my englisch is chopped u need to explain the a little more so i understand u correlty

real thunder
regal aspen
#

wtf

rich adder
#

backticks

scarlet pasture
#

no this is the wrong sysmbol

rich adder
#

literally copy them from the bot message

scarlet pasture
#

=> ``` <=

naive pawn
#

backticks are to the left of the 1 key on most keyboards, same key as tilde
if you can't find it, just copy from the bot message

regal aspen
#

will do

#

omg i just found it give me a moment

#
public class Laser : MonoBehaviour
{
    [SerializeField] private LaserData LaserConfig;


    private void FireLaser()
    {
        Physics2D.Raycast(Vector2(PlayerShip.transform.position, PlayerShip.transform.position), Vector2(10, 0));
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision = (gameObject.layer == 6))
        {

        }
    }
}
#

i'm not smart i'm so sorry

real thunder
naive pawn
regal aspen
#

trying to get it to recognize walls which have a specific layer

naive pawn
#

you're assigning a Collision2D to a bool?

naive pawn
#

if you want to check if it should collide, you don't need that collision = at all. just use the == in the conditional

regal aspen
#

neither of those work it gets mad with both

naive pawn
#

or better yet, set layer collisions properly so they don't collide if you don't want them to collide

naive pawn
polar acorn
naive pawn
#

collision = doesn't make sense at all

polar acorn
#

gameObject.layer == 6 is a yes or no question.
What you're asking is, "That object I collided with, is it a 'yes'?" which doesn't make sense

#

an object is not a yes

naive pawn
scarlet pasture
hexed terrace
#

there's no c in English!

regal aspen
real thunder
scarlet pasture
#

what is ugly? u mean u code?

real thunder
#

general solution

polar acorn
# scarlet pasture im not a englisch Speaker, im from germany. im honest with u i dont really under...

== means "Are these things equal". It gives you back a sheet of paper that says either "YES" or "NO"

collision is a collision event with an object. It's basically a big book of math formulas that says "Okay, you hit this object going this fast at this angle and so on".

You are asking if the contents of that book are the word "YES". Which it is not. They are not the same thing.

@regal aspen Further explanation as to the problem

real thunder
#

wrong guy btw

polar acorn
#

That should have been a reply to the other person, sorry

polar acorn
#

sorry

scarlet pasture
scarlet pasture
#

right to detect is the Animation done?

real thunder
#

I used OnStateExit because it's more stable

scarlet pasture
real thunder
#

but it looks bad, and using animation event would look bad, honestly, I am thinking if I should just use a timer

scarlet pasture
hexed terrace
#

Events are generally better than timers (depending on the situation) ...

In this instance.. you change the length of the animation and you either have to remember to update your timer var, or have something to update it for you.

An event will just fire when it's finished regardless, no thought beyond that required from you.

naive pawn
real thunder
#

you mean why I don't like them?
because they run on blending transitions unpredictably and I suspect they might be missed if something lags really hard

hexed terrace
#

yes, obvious missed word/ typo

real thunder
#

every section I read about animation events screams that I should not use them for crucial logic

scarlet pasture
scarlet pasture
#

can i ask u somthing

naive pawn
#

not with that attitude

#

!ask

radiant voidBOT
# naive pawn !ask

:thinking: Asking Questions

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

-# For more posting guidelines, go to #🌱┃start-here

naive pawn
#

just ask, don't ping random people. doesn't make me any more likely to help

scarlet pasture
#

Sorry

real thunder
#

so I only use them for sounds and visuals and to determine moments when to execute meleehit/shoot code

#

as for determining the moment when a mob must go from attacking to moving, nah

#

OnStateExit gives me that info nicely but the idea of using a script just for that looks silly

#

but I am getting an impression it's either that or timer

scarlet pasture
#

from Attacking to Movement u also can just use a "Has Exit Time" => 1

hexed terrace
#

Dont care about look of code in that respect.. care about functionality and move on

scarlet pasture
#

so the Enemy plays the Attack Animation and after it end exactly of the Attack Animation it goes to Movement if this u only 2 Animation it would work fine i think

#

im also not the best must i say but i think this would work

#

fine

real thunder
hexed terrace
#

you've gone too far

real thunder
#

in what direction

#

...I guess both

real thunder
#

yeah it repeats attacking instead of going to moving after each attack if player is in range

scarlet pasture
#

so u mean? the Enemy is Attacking conistently?

real thunder
#

if player is near it then yes

#

it loops attacking

scarlet pasture
#

and u dont want to reapeat the Attack Animation?

real thunder
#

I want it to stop attacking after it finished the whole animation

#

I don't think I will get an advice here how to make it better...

hexed terrace
#

What calls the attack in the first place?

real thunder
#
protected virtual void AttackLoop()
    {
        if (!animator.GetBool("attack") && animator.GetBool("isAttackEnded"))//attacking stopped go away
        {
            animator.SetBool("isAttackEnded", false);
            agent.avoidancePriority = RegularPriority;
            ChasingEnter();
        }
        else if (isWaitingToGoToTheStunState)//getting stunned
        {
            animator.SetBool("attack", false);
            StunEnter();
        }
        else if (ThinkingIsItWorthToKeepMeleeAttacking() && IsGoodAngleToMeleeAttack())//keep attacking here
        {
            UpdateRotationWhileAttacking();
        }
        else//deciding to stop attacking after next hit here
        {
            UpdateRotationWhileAttacking();
            UpdateAnimatorSpeed();
            animator.SetBool("attack", false);
        }
    }

anyway here is the code

scarlet pasture
#

but i want to help u

fickle plume
scarlet pasture
#

What even is this ```virtual ```` 🥀

#

hell nah im do bad for this hahahaah 😂

real thunder
#

it's a base class for all enemies so I override some methods for some

#

I am reusing a project I did like 2 years ago and I hate it tbh

scarlet pasture
#

what game are u making a 2d Game or 3D?

real thunder
#

3D

#

somewhat basic lame FPS

scarlet pasture
#

how long do u devolop Games?

real thunder
#

longer than I would want to

scarlet pasture
#

bro dont say that

#

gamedev is funn

#

i think

real thunder
#

till you realize you can do anything but it's years of tedious work

scarlet pasture
#

make a small game

#

i also do one

#

or do u mean to have the needed skills for a commectial game?

real thunder
#

it's not about commercial it's about general size and pool of content and mechanics

#

making something big - ton of tedious work

scarlet pasture
#

understand what u mean.

#

i also try to make a game currently but 2d art kills me so hard. also huge work

#

i got his!

real thunder
#

the personal problem is better I know that I can do stuff less interesting it is to do stuff

scarlet pasture
#

wait so lose u motivation if u know that u can make stuff?

real thunder
#

yes

#

learning is fun

#

doing (what you know how to do) is less fun

rocky canyon
#

knowing and doing are seperate things..
just because you know you can do something doesn't mean you're actually any good at it.. but i kinda get where your coming from

#

just gotta keep pushing your limits

real thunder
#

I never said I was good tho

rocky canyon
#

time-management is key to that too..
testing, discovery, implementation and so on..

need to arrange it so that the tedious bullcrap.. is in the midst of everything else 🙂

#

just trying to avoid burn-out i guess u could sum it up as

rocky canyon
scarlet pasture
#

i have a idea

#

we, yes WE ALL should make a Game... togehter

#

one big Game

#

what do u think?

#

me as a Leader with 10 ohter guys, we make a new Studio

tired python
#

can anyone tell me how can a Vector3, in this case transform.up be equal to a vector2 type object called direction

hexed terrace
#

it'll just auto put z as 0

tired python
#

as in if there were a vector2 object and i wanted it to copy the values of a vector3

hexed terrace
#

a vector3 into a vector2? I presume it would ignore z.. but dunno, try it and see

nocturne kayak
#

hello guys i'v made a small script to create a movement but the player is rotating on himself like crazy i guess its from the rigid body but i dont know what to do :)

rocky canyon
hexed terrace
#

If you're using a rigidbody, don't move with transform.position

rocky canyon
#

for (2) use the rotational constraints on the rigidbody you can lock individual axis

edgy sinew
#

Dynamic and Kinematic Rigidbody have different rules for how to be moved / rotated, to preserve interpolation & simulation accuracy

rocky canyon
#

def get rid of that extra collider whatever route u decide to take

nocturne kayak
#

Thanks everyone, I'll try to fix the problem :)

rocky canyon
#

unless its a trigger or something

nocturne kayak
#

I don't know if it's related to the collider or the rigid body , but my player goes up on its own when the script starts. ( the positions change)

#

i think its because of the character controller

rough granite
nocturne kayak
#

oops

tender mirage
#

Is invoke just the odd child of calling a function but it got an haircut and can't call functions with paramaters?

rich adder
#

uses reflection to find the function so its also kinda slower

#

if you want to call a delayed function (that supports parameters too) use Coroutine

tender mirage
rich adder
tender mirage
#

lol, but you just made me realize how redounded invoke actually is

#

shhhh, not you unityevent invoke. You're useful.

tender mirage
rich adder
#

the OG Delegate invoke the handy one

red igloo
#

In my game there are small zones where when the player enters them the camera changes to a different one to get a better angle. But the issue is when the camera is at a specific angle the movement input doesn't really match. For an example the player can move around normally when the camera isnt changed but in the image the camera has changed and to move left its S and not A. How do I fix this? should I make the movement camera relative?

tired python
#

where do i need to add this in the following piece of code?

using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    public float Thrust = 1f;
    Rigidbody2D rb;

    

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Mouse.current.leftButton.isPressed)
        {
            //Calculate mosue direction
            Vector3 MousePos = Camera.main.ScreenToWorldPoint(Mouse.current.position.value);
            Vector2 direction = (MousePos - transform.position).normalized;

            //Have player move in direction
            public float maxspd = 15f;
            transform.up = direction;
            
            rb.AddForce(direction * Thrust);

        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(gameObject);
    }
}



#

i don't want the object to go beyond a maxspd

rich adder
#

even tho thats pretty cringe

tired python
#

it says after addforce though

rich adder
#

yes after the AddForce. Under the }

#

this way it corrects any values AFTER addforce was added

tired python
#

wouldn't you want it to be correct before it reaches that state though?

#

or is it for the next loop

rich adder
#

its happening in 1 frame

#

usually

tired python
#

yeah, so if i am adjusting it for this frame after it adds the force, then suppose the force reaches 15.1, it already ends up applying it before it gets changed

rich adder
#

15.1 will be corrected right after

tired python
#

what the hell

#

sdfjsdklfjs

naive pawn
#

or what

tired python
#

i can't type

naive pawn
#

isn't accumulated force only applied to velocity upon fixedupdate

tired python
#

so what does that mean?

rich adder
#

Idk why unity wants to put this in update

naive pawn
#

also isn't there a maxVelocity

rich adder
#

but I guess it applies it and then by the physics frame is ready

tired python
#

can i tell you guys how i would do this?

#

and you tell me if that's an aight approach or not

rich adder
#

ops misread that

naive pawn
#

oh cool, physics2d doesn't have it

#

add it to the pile of discrepencies...

rich adder
#

this looks new to me

#

I always used Vector3.ClampMagnitude

naive pawn
rich adder
#

same thing as doing linearVelocity = Vector3.ClampMagnitude(current, maxSpeed)

rich adder
#

normally .velocity / addforce do belong in FixedUpdate so idk

tired python
arctic scarab
#

my unity says that I am trying to read Input using the UnityEngine.Input class, but I have active Input handling? How do I switch?

naive pawn
#

!input

radiant voidBOT
# naive pawn !input
How to Set Input

To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling

• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.

tired python
#

like i can blindly follow the tutorial but then, i won't understand what i am doing

rich adder
tired python
rich adder
#

its happening so fast practically unnoticeable

tired python
#

thx for the confirmation still

rich adder
tired python
#

like 14.9 vs 15.1 doesn't seem to be a lot of diff

#

imo

rich adder
#

maybe not always but depends how the tick / frame happened
i always assume its best doing it before the frame ends is best

naive pawn
#

well, across a lot of frames, yes that difference will matter

#

but with this specifically - i don't think it matters, because it'll all be processed in the simulation step thonk

arctic scarab
#

@naive pawn whats the main difference between new and old and which is more beginner friendly?

#

I switched to the old one

rich adder
#

Input is more tutorial friendly..
the new input system seems hard but its actually just as easy if not easier

#

there are just more ways to use it which make it seem complex

arctic scarab
#

ah, okay i'll use the old one for now

naive pawn
#

there is a learning curve to the new system but it's more flexible and imo easier to work with once you understand it

#

go with whatever the tutorial says for now, worry about this later

arctic scarab
#

alright

rich adder
arctic scarab
#

what in the, i made the movement script, but directions are off, might be the camera tho

scarlet pasture
#

Hey

arctic scarab
#

lemme just rotate it quick

naive pawn
#

saves us all a little time

rich adder
scarlet pasture
#

how can i detect that the Player is Moving but not like a extremly small moveinput. Like he is actually moving for a small value. I have this Case => i use a Character Controller!, do Unity have a build in function for that maybe?

scarlet pasture
#

dayumn

naive pawn
#

yeah, it was unnecessary

rich adder
naive pawn
scarlet pasture
rich adder
#

ya or magnitude of character velocity works too

scarlet pasture
rich adder
arctic scarab
#

I need advice on learning the keywords, for example GetComponent, like how do you memorize what each does? It feels like there is a billion of those words

rich adder
#

always best to use square magnitude though as its faster

scarlet pasture
rich adder
#

character controller or rigidbody

scarlet pasture
tired python
slender nymph
#

press the insert key

rich adder
scarlet pasture
#

and also would it make sense to also check "is the Player pressing A or D" so that somthing cant push the player and the Code thinks the Player is Moving.?

scarlet pasture
rich adder
#

if you only want to count as moving with keypresses / inputs then go for that

scarlet pasture
tired python
# rich adder you could do that sure, depends
transform.up = direction;   
rb.AddForce(direction * Thrust);

if (rb.linearVelocity.magnitude > maxspd){
    rb.linearVelocity = rb.linearVelocity.normalized * maxspd;
}
``` added this but this show s a compile error
naive pawn
#

cool, we aren't psychic though. what's the error, and which line

naive pawn
#

alright, you have something wrong above that

tired python
#

wasn't showing these errors prevouisly though

rich adder
#

you missed a { or }somewhere

naive pawn
#

look at where/what the first error is

#

it sounds like you missed a } on line 23

slender nymph
#

here's a hint: you can't declare public members inside of a method

rich adder
#

oh goodcatch how did I miss that in the screenshot

slender nymph
#

it's in their video when they were struggling with the insert key

rich adder
#

ah yeah you cannot use access modifiers inside of methods

#

the variables are defaulted to local and dont need access modifiers cause they're scoped (they dont exist outside the method)

tired python
#

then what's this abt

naive pawn
#

you put public float ... in the wrong place

tired python
#

public float maxspd = 15f;

rich adder
#

yeah most Unity lessons have assumption that one knows basic c#

#

you never put anything that has access modifiers (public, private etc.) inside methods and are usually fields

tired python
#

like what can be done and what cant

rich adder
#

using "public" on a local variable would not make sense, they only exists within that scope Method()

#

hence impossible to be public accessed elsewhere, so we make a field for that

tired python
rich adder
short gust
#

with Awaitables in Unity 6.0.x - can I assign a lamda function or delegate like with regular Tasks in C# to await them now/later and check for result when I need?
I'm new to async coding in Unity, even though I've used regular C# Tasks before.

rich adder
#

they should be able to be used the same ways no ?

#

I only used them a couple of times, mainly to switch up a task to be temporarily inside main thread to then do unity API stuff

red igloo
rich adder
#

soo iirc this wont work
Awaitable a = () => { ... };
but this should
Func<Awaitable> a = async () => { await Awaitable.NextFrameAsync(); };

#

and ofc you cannot use task specifc methods task.IsCompleted etc

wintry panther
#

Does anyone have a tutorial or guide on how to make kinematicbodies collide with other kinemtaic bodies? im trying to make a 2d car jam game where you drag different shaped blocks (like any rectangle shape or l-shaped blocks) and they are blocked by other blocks

short gust
wintry panther
#

i need the blocks to be able to be moved around freely but collide and slide

rich adder
#

I mainly just use when dealing with Unity specific stuff , like I mentioned the Unity events, or switching up backgroundthread thread to main, which is handy with unitys APIs (can only run on main thread)

rich adder
#

youd' manually need to detect it and prevent movement manually

umbral hound
#

Why is my rotation so slow? It's at a snail's pace

using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class Ball : MonoBehaviour
{
    private Rigidbody m_Rigidbody;
    private InputAction m_Move;
    public float m_RotationSpeed = 7f;

    private void Awake()
    {
        Application.targetFrameRate = 60;
        m_Rigidbody = GetComponent<Rigidbody>();
        m_Move = InputSystem.actions.FindAction("Player/Move");
    }

    private void FixedUpdate()
    {
        Vector2 vector = m_Move.ReadValue<Vector2>();
        Vector3 movement = new Vector3(vector.x, 0f, vector.y);
        m_Rigidbody.AddForce(movement * (m_RotationSpeed * Time.fixedDeltaTime), ForceMode.Force);
    }
}
short gust
rich adder
#

yeah exactly thats the main selling point for me

rich adder
#

AddForce is already moving on Tick fixed Delta

#

you're essentially adding it twice

umbral hound
#

oh okay

#

did not know that, thanks

scarlet pasture
#

hey, i wanted to programm that the backround layer "Moves" with the Player. can i just say Lerp with the Player position but just a little bit slower for each layer?

#

and if the Player stand, i increase the follow SPeed so the Lerp Catches up faster

#

i mean is this the Logic behind?

frail hawk
#

are you looking for a paralax effect?

scarlet pasture
#

YEAH! this is what i search better said

#

is my thought correct? better said my plan?

#

what do u think?

wintry panther
frail hawk
#

just look for paralax tutorials it is easy to achive.

scarlet pasture
#

yeah, i want to programm first my thought and after asking here. i learn better with this waqy

#

i mean i can try it why not

rich adder
#

isnt it just different backgrounds at different speeds, in its most simplest form

scarlet pasture
frail hawk
#

the z axis is your friend

rich adder
scarlet pasture
rich adder
#

some like Movespeeds
background_back = 3f
background_mid = 5f
background_foreground =7f

queen adder
#
    private void OnValidate()
    {
#if UNITY_EDITOR
        EditorApplication.delayCall += () =>
        {
            for (int i = transform.childCount - 1; i >= 0; i--)
            {
                DestroyImmediate(transform.GetChild(i).gameObject);
            }
            if (!debugSheres || vertices == null || spherePrefab == null) return;
            foreach (Vector3 pos in vertices)
            {
                GameObject sphere = Instantiate(spherePrefab, pos, Quaternion.identity, transform);
                MeshRenderer renderer = sphere.GetComponent<MeshRenderer>();

                Material newMaterial = new Material(renderer.sharedMaterial);
                newMaterial.color = new Color(pos.x, pos.y, pos.z);
                renderer.sharedMaterial = newMaterial;
            }
        };
#endif
    }

Why is it so slow to update? The value is being updated quickly but the spheres are updating at maybe 3fps. Is it the fact that I'm creating and destroying gameobjects?

tired python
#

i want this booster to appear only when i left click, but it does not appear when i click it

scarlet pasture
# queen adder

maybe because u change the vlaue in the Inspektor and than u dont change the inpektor for a sec. Unity register that and use u OnValidate to Updated it

#

but im not totally sure.

rich adder
tired python
rich adder
#

the script Player should be on gameobject Player, not on the booster

rich adder
tired python
rich adder
#

yes but thats the old , show what you changed

tired python
rich adder
tired python
rich adder
#

with the reference assgined?

#

show

tired python
#

the other things work fine, just this booster

rich adder
#

this doesnt show the reference

#

expand the script

tired python
rich adder
#

not the code, uncollapse the Player component

tired python
#

then?

rich adder
#

screenshot

tired python
rich adder
#

jesus

#

do you know what uncollapse means?

tired python
#

i uncollapsed it..

#

oh wait

#

its the opposite

rich adder
tired python
#

oh

#

wait that actually worked

#

thx

rich adder
#

hhuh

tired python
#

i was gonna ask, how does the pc know that the booster is the game object

rich adder
#

lol uncollapsing it has no effect , i just wanted to see the reference was assigned

tired python
#

i assigned it after you asked

tired python
rich adder
#

oh exaclty, did you not check console probably spammed a few Null Reference Exception

#

usually first place to look when its not working

#

keep the Console window visible

rich adder
scarlet pasture
#

u also can use Error Pause, so its frezzes the Game if u have a null reference

tired python
#

the guide told me to use this layout...

tired python
rich adder
#

the layout is fine just make sure you pop the Conole tab somewhere visible, its pretty important

#

its hard to catch the messages if they are just a footer of the app

scarlet pasture
#

but its better if u check it out if u start the game

rich adder
#

I mean you still wanna keep the console there open at all times

#

thats your lifeline to the "backend"

tired python
#

can't i use the UI thingies which the project inspector and other tabs use?

rich adder
#

drag the tab where you want it

#

no need to undock it

scarlet pasture
#

u can do this

#

make them into one, it saves space

tired python
#

thing is, i can't get it to work the way the other tabs do

rich adder
#

yeah but then its not open at all times especially with Project view

#

best to keep it there

#

eg hers mine

tired python
#

nvm

#

got it to work

#

you guys have massive screens

rich adder
#

i'm on a 13 inch macbook

scarlet pasture
tired python
rich adder
tired python
#

nice

scarlet pasture
twin pivot
#

Its very retro

tired python
#

the mouse showing is a bit eee though

rich adder
#

ya it was a 1 bit jam but ended up missing out on the deadline so Im gonna make it a smaller game

tired python
#

i remember wizard legends using a similar thing, didnot like it

rich adder
queen adder
#

Is there some sort of standard to creating a square mesh for procedural terrain?

vertices[x]     = new Vector3(0f, 0f, 0f);
vertices[x + 1] = new Vector3(0f, 0f, 1f); // z first
vertices[x + 2] = new Vector3(1f, 0f, 0f);
vertices[x + 3] = new Vector3(1f, 0f, 1f);

vertices[x]     = new Vector3(0f, 0f, 0f);
vertices[x + 1] = new Vector3(1f, 0f, 0f); // x first
vertices[x + 2] = new Vector3(0f, 0f, 1f);
vertices[x + 3] = new Vector3(1f, 0f, 1f);

Is one better than the other? Am I overthinking this?

shell sorrel
#

and that part is done in the trinagle array anyways

queen adder
#

alright

#

fair enough

shell sorrel
#

the 2 triangles to make the quad should have things winding in clockwise

dreamy scaffold
#

Can someone help me with this error? I have already tried deleting the library and regenerating my project files, but nothing seems to fix it

#

Any help is much appreciated

shell sorrel
#

also you do not want to be using the UnityEditor namespace in your game logic code

dreamy scaffold
#

I just realized that was the case...

#

Nvm it looks like it is able to build now, ty for the help. I completely missed that for some reason.

shell sorrel
#

its only around while in editor

rich adder
#

Unity basically strips those when you build

swift crag
#

this often happens when your IDE gets a little too helpful and adds a using directive when "fixing" a typo'd name

#

shoutouts to this one in particular

chrome apex
#

stupid question, is there a way to look at a transform or collider of an object while moving another object in scene view?

shell sorrel
#

can change one of thse options to give it a icon or show a name in scene

swift crag
#

You can right click on an object in the hierarchy and hit Properties... at the bottom

#

This will open a new inspector panel that displays that object

#

You can also lock the inspector to prevent it from switching to another object

scarlet pasture
shell sorrel
#

that works as well

#

hmm actaully collider gizmos only show for selected

#

does not matter if it still has a inspector focused on it

#

i have before jsut added a component that literlaly just draws gizmos then removed later

chrome apex
scarlet pasture
#

u can use 2 Inspektor, i think...

swift crag
charred spoke
#

alt shift p also pops out a locked version of the inspector for the selected object

swift crag
#

ooh, handy!

charred spoke
#

Changed my whole unity experience when I learned this 🤣

chrome apex
#

Guess I can just open up another scene view

#

oh wait,

#

I can do it the other way round

scarlet pasture
#

hey, i want that the leaves fall out of the tree, for a better atmosphere. isit normal to just instaitate them and use the Animation for each Leave?

#

this would be bad for performance right?

chrome apex
#

I can lock the inspector of the first object and instead of moving it with the scene view arrows, I move it via the transform component and have the other one selected

swift crag
charred spoke
#

Very bad yes

scarlet pasture
charred spoke
#

A particle system is what is usually used for this kind of thing

charred spoke
polar acorn
#

It'd be weird if you didn't

charred spoke
#

I’ve done leaves with meshes as well

scarlet pasture
#

if i use a particle effect, would that also allow to animatie the leaves?

swift crag
#

Yes, you can do quite a few things!

#

You'll want to plug the Sprite assets into the Texture Sheet Animation module of the particle system

shell sorrel
#

with the write sheet layout you can even randomly choose a row and animate across it over lifetime

scarlet pasture
#

and what would be the dirffrence? between a normal Animatiatead leaves and a Particle System Animated leave

swift crag
#

your game wouldn't be full of hundreds of tiny game objects :p

#

particle systems also make it very easy to create a variety of effects

shell sorrel
#

particle system is greatly more effecient and can do huge numbers of that at little cost

swift crag
#

e.g. wind, collision with surfaces, fadingi n and out

shell sorrel
#

and isntead of hand animating you can apply forces and noise

swift crag
#

they're incredibly useful (i mostly work in VRChat right now, and you can pull off a ton of stuff without any scripting)

scarlet pasture
#

Thanks i will try it

shell sorrel
#

in almost all engines its like the stadard way to handle, smoke, sparks, leaves, dust, rain, snow etc

wintry panther
#

im using a kinematic rigidbody and calling movePosition() and detecting collisions manually, but when the object detects a collision with another kinematic rigidbody there's slight gaps between them. does anyone know how to make pixel perfect collisions?

scarlet pasture
#

im not sure but u can try Collision Continues

#

but im not sure this woul work

wintry panther
#

im using continuous

#

super messy code right now but im just trying to get the functionality working

devout garden
#

does anyone know how I cant cut a clean square hole in this pro builder shape (its a hollow block representing a hallway)

#

bc I need rooms

twin ember
#

Hey! Just quickly looking to work out if something like this infinite zoom effect should be done with some kind of visual shader, or a script to warp the geometry? My plan was to have the player be stationary where they only orbit the center at a fixed distance, then scale up the geometry, but looking at the center, it scales up really fast, then slows down when approaching the player. Thanks! https://www.youtube.com/watch?v=4sAft1zecHk

Infinite Pizza - Slice Deep Into the Cheesy Heart of an Infinite Pizza in this Eye-Melting Game!
Read More & Play The Full Game, Free: https://www.alphabetagamer.com/infinite-pizza-game-jam-build-download/

▶ Play video
scarlet pasture
#

Just finished my combat system in Unity — would love a quick review or feedback, im currently also building a SwordMode. And thanks for any help, im improved my skills alot. and i know i use Linq in this Script. im just need to change that in the future.

#

!Code

radiant voidBOT
scarlet pasture
#

my Goal is to make a Scalable Combat System for a 1-3 Month Game.

swift crag
#

so, if your current scale is 1, you change twice as fast as when the scale is 0.5

#

this means that it takes a fixed amount of time to double in size

#

if you just add to the scale at a uniform rate, each doubling takes twice as long

#

I'd consider calculating the scale directly with a function like this

#
float startScale = 0.01f;
float startTime = 0;

void Update() {
  float lifetime = Time.time - startTime;
  transform.localScale = Mathf.Pow(2, lifetime) * startScale * Vector3.one;
}
#

this doubles once per second, so it'll reach a scale of 1 after log2(100)=6.6-ish seconds

#

If you need to start out at zero scale, you can lerp in from zero

#
Mathf.Lerp(0, 0.01f, lifetime);

this would go from 0 to 0.01 over the first second

twin ember
swift crag
#

(and then stop growing, because lerp is clamped)

twin ember
#

This seems to show the tin on the left totally warping like a central vanishing point drawing

swift crag
#

That might be better done in a shader then, kind of like how you'd do a curved world for an infinite-runner game

#

Each vertex is getting scaled down separately based on its distance from the origin

twin ember
swift crag
#

You want the obstacles to actually change in size over time, so that they can bump into the player. So you might wind up doing both:

  • Each object starts with a tiny scale and grows exponentially over time
  • The shader shrinks vertices on the Y axis based on their distance from the center
#

So, for example, the "pizza slices" in that screenshot would actually have a uniform height – like a slice of cake

#

but the shader would then squish them into a wedge shape

twin ember
#

OH that's a good idea, so then the pinch effect is purely Y scaling from the shader, which seems like a really good approach. Thank you!

swift crag
#

So you'd start out just scaling up objects, then throw in a shader graph that does something like this:

  • measure the distance from the world origin
  • remap that into the 0..1 range (maybe just use Inverse Lerp + Clamp; i forget if there's a remap node)
  • multiply your world-space Y position by that
twin ember
#

Sounds like it actually isn't as hard as I expected, tysm, I'll give it a go

swift crag
#

no prob (:

glad shore
#

how do i get the main parent of a gameobject

polar acorn
#

.transform.parent

glad shore
#

but that gets the parent of the object, i want the main parent even if its being held by multiple parents

tired python
glad shore
#

actually fixes all my problems ✌️

polar acorn
glad shore
#

yeah, i was looking for a way to get the topmost parent in the hierarchy. I was trying to organizing my hierarchy way more without it

scarlet pasture
charred monolith
scarlet pasture
#

ja bro

charred monolith
#

nice

scarlet pasture
#

hahah endlich mal einen deutschen getroffen hah

#

was würdest du mir als tipps geben?

#

will unbeding besser werden auf ernst atp

grand snow
scarlet pasture
#

sorry, i said to him, "Can u pls rate my Code and give me some Tipps, i want to be a better Coder"

eager elm
scarlet pasture
#

what is a megic number?

#

okay i will try to have to make them in seperate Scripts. Thank u bro!!!!

eager elm
#

the numbers in your Update switch statement like 0.34. Only you know what they are supposed to be. You should define them as variables at the top so it's clearer, like, I am assuming:
float cooldownRecoveryTime = 0.34f;

scarlet pasture
#

so i can defint the float values if i want

charred monolith
scarlet pasture
zenith wren
grand snow
zenith wren
#

ah I see

#

at this point contemplating to just transfer everything to 2022 version

grand snow
zenith wren
#

ah I see

urban ocean
#

Hi guys! I'm new to game developing and I wanted to practice with some of the most famous softwares so I chose Unity bc I heard that it's good to get started and do simple stuff. I'm also new in coding in general and I wanted to know which tutorial did you use to learn Unity, any advice you can give me from personal experience etc would be well accepted, thank you and see ya

zenith wren
#

for me what worked the best was doing the official unity course

radiant voidBOT
zenith wren
#

this

urban ocean
#

oh and it is free, thank you very much guys!

inner elbow
#

hey i joined this server just now so i could get some help with a game im developing. its a 2d game and its in its early stages, right now im looking for help with programming a wall jump. could anyone help with that?

cosmic dagger
sour fulcrum
#

might need to elaborate on what "whoever wants them" and "everyone" is in this context

bleak wadi
#

How do I connect visual studio to Unity? Unity classes are not highlighted

delicate onyx
radiant voidBOT
pallid linden
#

Hi! I am creating a package and I would like that, after installing it, the system changes automatically (or prompts the user to change) the Active Input Handling setting to "Both" instead of only using the old input system. I've tried looking this up but I haven't found an answer. Any help is appreciated!

grand snow
pallid linden
grand snow
#

I cant see this as something that can be changed in code. Some things just aren't. You could just edit the file directly but may cause issues

fast relic
vast comet
#

Hey, I was wondering if its possible to avoid these cracks between rails, using Unity's spline instantiate. If I make the rails more frequent, it wont be smooth.
Any way to make procedural rails?

pallid linden
fast relic
pallid linden
# fast relic you can probably also add a button to open the player settings window if you're ...

I found that I can use this:

bool openSettings = EditorUtility.DisplayDialog(
    "Enable Both Input Systems",
    "This package requires Unity's Input System and the old Input Manager.\n\n" +
    "To avoid input issues, please open Player Settings and set\n" +
    "Active Input Handling to \"Both\" under 'Other Settings'.",
    "Open Player Settings",
    "Later"
);

if (openSettings)
{
    SettingsService.OpenProjectSettings("Project/Player");
    Debug.Log("Go to 'Other Settings → Active Input Handling' and set it to 'Both'.");
}
else
{
    Debug.LogWarning("Active Input Handling may not be set to Both. " +
                     "Some input features might not work correctly.");
}
fast relic
#

yeah that should work

grand snow
#

cant wait for most things to ditch the old system

fast relic
#

i think the issue they're having is that some people have it set to old and not new?

#

sorry if i'm misunderstanding

#

and it didn't work because their unity client had it by default as the old input system

grand snow
#

yea, only recently will new projects default to input system.
But having both be around isnt great especially if you want to target a platform that cannot use "both"

fast relic
#

yeah the new input system is ideal to use but i can understand people either being stubborn or legacy projects that are a pain to migrate

pallid linden
#

I think it's about time to use only the new input system

fast relic
#

definitely yeah

pallid linden
#

Also, a bit off topic but why do we still have to install TMPro as an extern package?

#

Shouldn't it be Unity's default?

fast relic
#

i never had to?

grand snow
#

Nah in unity 6 its inside unity ui

#

but before it was its own package

pallid linden
#

But even in Unity 6 I get the prompt "you need to install TMPro essentials"

#

And I think that the "Text" class is still different from TMPro

#

Shouldn't they be like unified by now?

fast relic
pallid linden
#

True

fast relic
#

probably so you don't have extra stuff clogging it up if you don't wanna use tmpro (ui toolkit or legacy text)

fast relic
grand snow
#

ugui Text is the legacy one

#

and tmp essentials is needed to add some shaders and stuff

#

if using UGUI you want tmp, legacy text is poo poo

pallid linden
#

I haven't seen a single project using legacy text, they all go TMPro so that's why I wondered why it wasn't just replaced by that

#

(at the same time I'm not that experienced so I cannot say I know much)

fast relic
#

so that if you're migrating an old project that doesn't use it it doesn't just break completely

pallid linden
#

That makes sense

fast relic
#

but tmpro is the one that should be used

night raptor
# vast comet Hey, I was wondering if its possible to avoid these cracks between rails, using ...

I haven't used the spline package myself much but I don't think you can get away with just instantiating blocks on the spline. Even if you make the blocks be closer, the transition won't obviously be perfect. I would rather make the spline by repeating and actually deforming the rail and then instantiating these parts separately (assuming it is not possible to do that directly with the package, I don't know)

grand snow
#

Its somehow not functionality offered by the splines package

night raptor
#

what isn't? (just asking)

grand snow
#

they do have some mesh generation stuff (inc a road) but nothing to deform a mesh along a spline

#

I feel like the ideal solution for a railway track would be mesh extrusion along a spline

night raptor
#

Oh unfortunate. Maybe should use one of the countless spline assets out there then that support that, the unity one might not be great then

#

Yeah, I mean of course making your own mesh generation using the unity splines isn't horribly difficult to do though

night raptor
grand snow
hexed terrace
#

This is a code channel. Delete and ask in #📲┃ui-ux -> with screenshots of your setup

remote mountain
#

ok

tired python
#

so i set the restartbutton to be invisible when the game starts.

#

and be visible only when a collision happens

#

but somehow, the restart button keeps appearing at the start

wintry quarry
#

It's a little odd though - which script is each of these snippets from and which object is that script attached to?

tired python
#

Like this?

wintry quarry
#

I would do it as the first line

#

Not the last

tired python
#

oh wait

#

i don't think that's the problem, cus the explosion effect doesn't play unless a collision occurs

wintry quarry
#

Check anyway

tired python
tired python
#

lemme check

wintry quarry
#

Because from that error it looks like you don't have a valid reference set up

tired python
scarlet pasture
#

u only want to kill the player if he is colliders with the rocks?

tired python
scarlet pasture
#

if yes u should also make sure that u only allow collisions with spezifical Objects

tired python
#

not for now...

#

the tutorial only tells me to destroy it whenever it collides with any objects

#

even the outline

#

i will get to it once i complete the tutorial

#

i don't want to end up messing the code and then resulting being stuck to find out what i did wrong

scarlet pasture
#

did u maked sure that the Ui is visible to false befor the game starts?

scarlet pasture
#

hmmm im also new but can u share a picture of u player? and all of his child objects?

#

because right know u allow collisions with everthing, if u have a chiled or somthing in the scene thatz does have a collider u run the onTriggerEnter Method.

tired python
scarlet pasture
#

under the player have this colliders?

tired python
#

once i get through this, i will do that

scarlet pasture
#

u can do that but u problem is that the restart button apears even u didnt collide with the rocks

#

u have child GameObject with a collider?

tired python
#

yes

scarlet pasture
#

yes or no?

tired python
#

yes

#

it's called rb

scarlet pasture
#

rb? is rigidbody2d

tired python
#

``Rigidbody2D rb;

fast relic
scarlet pasture
#

i mean "Collider"

#

if u child has some Colliders => "u player collides with them and this run the trigger methode"

tired python
#

nah, i don't think i have it rn

scarlet pasture
#

go check it out

tired python
scarlet pasture
#

u see, this is a collider2d if any of u Childs have this u trigger metod runs if u child has "Is Trigger" to true

tired python
fast relic
#

the goal of a (gamedev) tutorial is not to get a game out of it, it's to learn how to make games yourself

scarlet pasture
tired python
#

wait a sec

tired python
tired python
scarlet pasture
#

i wish i had better englisch skils, i think i would understand everthing better.

tired python
tired python
scarlet pasture
#

nahh bro

tired python
#

bruh i am new tooo...

scarlet pasture
tired python
#

yes i did do that

scarlet pasture
#

to the childs?

#

not the player! the childs!!!

tired python
#

childs

scarlet pasture
#

okay

#

u code is thinking i "Collides with my self" so i need to use my Trigger code and make Ui visible

tired python
#

ok...

scarlet pasture
#

IM NOT SURE, im really not the best but u need to make sure that u only allow collision with spezifical objects

tired python
#

i do get what you are saying, currently the code destroys the object for every 2d object it collides with, i would want the object to only destroy if it collides with certain objects...

scarlet pasture
#

other is the name! of the function

#

if.other... (that mean if this script lies on the player!!!!, detect is somthing collides with ME!#

#

i want to detect gameobjects and i want to compare my Tag with the other tags. if they have the Tag "Rocks" run my code

#

my tag is as a example "player"

#

and the stuff that should kill me have this example this Tag

#

bro sorry... im to bad to explain somthing....

rugged beacon
#

theres collision matrix to exclude collider collide in different layers

#

or the include exclude box in the collider component

scarlet pasture
#

yeah but he dont want to ignore them

#

i think he is currently colliding with him self, and he dont have a safty check befor the "Ontriggerenter2d" code runs

tired python
rugged beacon
#

its the same as you doing if(tag) then execute

tired python
#

the game runs, problem is the restart button ain't working

scarlet pasture
#

but u had child that has a collider and a trigger??

tired python
scarlet pasture
#

oh

rugged beacon
#

this your player? every child has a collider?

tired python
#

i only did that because you told me to...and after i did check the trigger for the child objects, my spaceship started to go trhough them and not explode

scarlet pasture
#

no i just asked do u habe enabled the istrigger#

#

i didnt said u should do that

tired python
#

i did not have the trigger enabled xD

scarlet pasture
#

good

rugged beacon
#

are the child overlap themself ?

scarlet pasture
#

so u only problem is that u restart button are not working?

tired python
scarlet pasture
#

what is not working`?

tired python
rugged beacon
#

triangle or square there in your player, are ther collider touch each other, if yes then your player is colliding with itself

scarlet pasture
#

AND u are 100% sure that now any of u child has a trigger AND istrigger is false

scarlet pasture
rugged beacon
#

idk brother same

scarlet pasture
#

looks fine to me

tired python
#

the restart ain't fine

scarlet pasture
#

where is u ui gameobjects?

#

better said what controlls u ui?

#

what Script controlls u UI*

tired python
#

are you asking for the script?

scarlet pasture
#

yeah

tired python
scarlet pasture
#

this also controlls the restart button right?

tired python
#

yes

rugged beacon
#

the code inside the script?

tired python
#

yes

rugged beacon
#

i mean can you show it

tired python
scarlet pasture
#

maybe u coded somthing wrong can u post it

rugged beacon
tired python
rugged beacon
#

void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("Restart Button is Displaying.");
Destroy(gameObject);
Instantiate(ExplosionEffect, transform.position, transform.rotation);
RestartButton.style.display = DisplayStyle.Flex;
}

can you try comment this out? see if the collision the problem here

#

the whole thing

cosmic dagger
radiant voidBOT
rugged beacon
#

well you see, its already show up

tired python
#

exactly

rugged beacon
#

its not about the collision

tired python
#

yes...where did i go wrong

rugged beacon
#

your reference is wrong maybe then

tired python
#

RestartButton = UIdoc.rootVisualElement.Q<Button>("RestartButton"); this thing?

rugged beacon
#

i think so, debug log the button see if its null

#

i havent done uitk before

tired python
#

it does print null when i collide...

rugged beacon
#

check your naming and stuff

scarlet pasture
#

can u show what error u get

tired python
#

yes, it does show null reference error

scarlet pasture
#

so maybe u code dont find the ui

#

can u show the error log

tired python
#

prolly naming problem

thorn holly
#

What’s the null ref

tired python
scarlet pasture
#

click there two time and see to what lines it brings u up

#

u didnt assing somthing

rugged beacon
#

its the button

tired python
#

Player

scarlet pasture
rugged beacon
#

brother fix your button reference

#

naming and stuff

scarlet pasture
#

S1nth did u clicked two times at the references, it should opent the code and shot to u eactly whitch line dont functioned

#

okay nice now opend the player and look

#

whitch variabel u need to assign

#

i think this can be the problem

tired python
#

private Button restartButton; it's private

#

i can't access it through player

#

it doesn't show restartButton in the list

thorn holly
rugged beacon
#

check if the right side thing correct

scarlet pasture
tired python
rugged beacon
#

idk havent done UITK before, did you not know what to put in there in the first place...
try rewatch the guide you follow

tired python
#

RestartButton = UIdoc.rootVisualElement.Q<Button>("RestartButton"); just tell me what name is the "RestartButton" supposed to refer to?

rugged beacon
#

what ever name in your ui doc

tired python
rugged beacon
#

... please rewatch and understand the guide you follow

tired python
#

oh wait, that's PlayerController.c

#

found the problem, this thing is what is supposed to be in that string

#

RestartButton = UIdoc.rootVisualElement.Q<Button>("Button");

#

it's working

#

thx guys

#

@rugged beacon @scarlet pasture

rugged beacon
#

type shi

tired python
#

i want to add the functionality of the total energy being conserved before and after collisions so that the momentum of individual asteroids doesn't die out...

#

any ideas as to how i should do it?

#

it's not in the tutorial...

thorn holly
tired python
#

that does happen but that's fine with me, it looks good. suddenly pausing everything would seem awkward

#

what i do want to happen is that, after a bunch of collisions, the momentum of the asteroids dies out, and then they come to a stop

thorn holly
tired python
scarlet pasture
#

u mean when two rocks collides ther bounce of and lose the energy for moving?

#

okay i think u only need to give the rigiobody a bouncy value heigher then 1

#

but im not sure, like i said im also new

thorn holly
tired python
#

i will try it then

thorn holly
#

Which is prolly simpler tbh

#

I’d do the physics material

tired python
#

lower than 1 or more than 1

thorn holly
scarlet pasture
#

in the interent u can see other people solve this provblem with code

#

but its very hard, they use a mathimatical way

scarlet pasture
tired python
#

i don't want the collisions to die out

scarlet pasture
#
    {
        var rb2 = c.rigidbody;
        if (!rb2) return;

        Vector2 n = c.GetContact(0).normal.normalized;

        float m1 = rb.mass;
        float m2 = rb2.mass;

        Vector2 v1 = rb.velocity;
        Vector2 v2 = rb2.velocity;

        float u1 = Vector2.Dot(v1, n);
        float u2 = Vector2.Dot(v2, n);


        if (u1 - u2 <= 0f) return;

        float u1p = ((m1 - m2) * u1 + 2f * m2 * u2) / (m1 + m2);
        float u2p = ((m2 - m1) * u2 + 2f * m1 * u1) / (m1 + m2);


        Vector2 v1p = v1 + (u1p - u1) * n;
        Vector2 v2p = v2 + (u2p - u2) * n;

        rb.velocity = v1p;
        rb2.velocity = v2p;
    }
}```
#

they used this.. waht ever this is 🥀

thorn holly
tired python
#

i don't want that to happen

scarlet pasture
#

no he mean that if they collides (the rocks they never stop moving) and lose the energy

#

i think...

thorn holly
tired python
tired python
#

oof

scarlet pasture
tired python
#

i think it's this formula that they are trying to replicate using code

scarlet pasture
# tired python

Helllll nahhh bro forget to asing a value but know this shit

thorn holly
tired python
#

the variable names match

scarlet pasture
#

🥀

thorn holly
# tired python

That’s really unecessary, unitys physics does it for you

tired python
scarlet pasture
#

yeah he is definetly right, the code looks also very hard to understand. for me tbh

thorn holly
#

Just use a physics material with bounciness of 1, make sure you set bounce combine to maximum

#

Then add it to ur asteroids

#

You could also set friction to zero and friction combine to minimum to ensure no energy is lost from friction

tired python
#

ofc, you wouldn't be using it but u know, if it fascinates you...give it a shot

scarlet pasture
#

and im 100% i will need that in the Game Devolopment in the future

#

for nice levels i think

tired python
#

yes

#

i mean...kinda depends on what you call new. i am new compared to most people in here soo....

scarlet pasture
#

HAHAHAHA

low copper
#

Hello everyone, I've got a silly beginner question for you all. I'm trying to have a class with the following property:

private string[] cubeState { "one", "two", "two", "one", "two", "two", "one", "two", "one", "one", "two", "one", "two", "one", "one", "two" };

Based on my readings that is not possible, I need to do something like this :

public string[] cubeState { get; set; }

and then assign / edit values later...

cubeState =  new string[] { "one", "two", "two", "one", "two", "two", "one", "two", "one", "one", "two", "one", "two", "one", "one", "two"};
cubeState[4] = "two"

I just wanted to check, is this really the only way? I spent time reading and couldn't confirm if I had other options?

vital barn
#

public string this[int index] ???

maiden drum
#

Is there any way to add a contructor to monobehaviours before initialization?
I hate adding an Init() function after because i can see myself forgetting to call it, and it increases implicit knowlage. Same for manually adding the variables.

There's the possibility of adding an alternative instantiate function for the objects, but i'd rather not if there is an easier solution

thorn holly
low copper
low copper
vital barn
maiden drum
#

you forgot the =

#

if you just want an array with certain values

vital barn
maiden drum
#

i think he's trying to initialize an array with values

low copper
#

I could have swore I tried that and got errors. Thank you!

maiden drum
#

np mate

low copper
#

For your question...none of the Monobehavior methods work for initialization? Awake() or Start()?

maiden drum
#

nah i meant adding a required argument, for example Bullet(speed, damage, whatever)

#

unfortunately you need addComponent / instantiate and then either assign the values or add an init() functions, can't really add required params

vital barn
#

The only alternative is to have your own shell over the component system.

#

Or a method that accepts generic interfaces

maiden drum
#

yeah, i think just add a wrapper for the objects that i want to force arguments on.

Essentially i want weapons to pass the bullet stats SO the the bullets they pool/instantiate, since i'm reusing the same prefab for multiple weapons. And i can see myself forgetting inits() when writing new weapon scripts in the future

#

when i'm thinking about it, probaby a base class would be enough, there won't be neccessarily any bullet creation logic changes between the weapons,

vital barn
#

But to be honest, the need for Inits methods is not even a problem.

maiden drum
low copper
#

@maiden drum : Sorry if I'm just wasting your time...I'm pretty new to all of this...but maybe you could do an abstract class that grabs the bullet data for that particular game object from some data source

#

and just extend off it

vital barn
maiden drum
#

i'm thinking of doing something along the lines - just have a base class with methods shared across weapons, one of them being the bullet creation logic + stats "passdown" and every additional weapon script can just call the base class's function

maiden drum
tender mirage
#

Is there any reason why my coroutine isn't stopping? the stopCoroutine should trigger, but it doesn't in this case

using UnityEngine;
using System.Collections;
public class PlayerPropella : MonoBehaviour
{
    private bool isPropellaSpinning;


    //Component
    [SerializeField] private SpriteRenderer propellaRenderer;


    //Stored current sprites
    public Sprite[] propellaSprites = { null, null, null, null };

  
    //Called from event
    public void StartPropella()
    {

        print("Propella activated");
        
        if (isPropellaSpinning == false)
        {


            StartCoroutine(PropellaSpin());
        }
        
        
    }


    public void StopPropella()
    {
        isPropellaSpinning = false;

        print("Propella stopped");
        
        StopCoroutine(PropellaSpin());
        
    }



    private IEnumerator PropellaSpin()
    {
       isPropellaSpinning = true;


       int CurrentFrame = 0;

        while (true)
        {
            propellaRenderer.sprite = propellaSprites[CurrentFrame];


            //print(CurrentFrame);

            if (CurrentFrame < propellaSprites.Length - 1)
            {
                //Increase frame
                CurrentFrame += 1;
            }
            else
            {
                //Reset
                CurrentFrame = 0;
            }

            

            yield return new WaitForSeconds(0.1f);
        }




        yield return null;
    }

}
vital barn
#

StartCoroutine returns Coroutine handle use it or call StopAllCoroutines

cosmic dagger
tender mirage
vital barn
#

It heed coroutine handle

tender mirage
#

You mean the Keyword Coroutine?

vital barn
#

Which is returned by StartCoroutine

vital barn
#

In UnityEngine

tender mirage
vital barn
#

yes

tender mirage
#

So something like this?

vital barn
#

Yes

tender mirage
#

yeah. not used to using that. i need to learn it

#

thanks for the help

#

also fumo.

#

🫳

maiden drum
cosmic dagger
tired python
#

i have a question, i have two collision effects. First one for when my player object collides with other 2d objects (resulting in it being destroyed) and second one for when other 2d objects collide with each other ie asteroids with each other or asteroids colliding with the background. I want to add an effect for when the latter happens. How do i set it such that when certain objects collide with each other, a specific collision effect occurs?

tired python
vital barn
#

Google

tired python
#

wait, that does not make sense

#

ofc i am going to use a diff tag for diff collisions

#

my question is, how should i code it out in a way such that only when certain 2d objects collide, does a specific collision effect happen