#💻┃code-beginner
1 messages · Page 755 of 1
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.
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.
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)
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
bump
yep, so i get fail-fast behaviour.
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.
what is fail-fast behavior?
I noticed fallbacks are something that AI likes very much when refactoring code. So perhaps that's where you got it from? 😏
yeah, in my first weeks i use ai alot for Synatx etc
"if something goes wrong, stop and give me an error message that tells me what went wrong"
you said it's not clear where it's called, so I sent the line it's called from
Used in EventType.MouseDown and EventType.MouseUp events.
fromEvent.button
so yeah that just.. doesn't work
What I meant is, that it's not clear where unity calls it. Unless that callback is invoked in your code..
yeah, I was just trying random stuff from recommendations, which didn't work, so I am asking for help now
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
(this is how UI events work in general, not just unity)
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.
not sure where you got that suggestion from
here
im not the same person as dlich
I have a question, How do you implement jump mechanics in 2D top-down?
well yes, but it happened during the same conversation and that's all the info I have, I am fully open to other suggestions
that's kinda a design question rather than a code question, no?
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
you need to store that separately
you just need to keep a state between events
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)
really small asset you are supposed to just import into the project and it works.
well i mean, you modified it to make it not work lmao
Considering it's in editor, there's likely an event you can hook to on input or at least some callback where it's routing the input data.
Are you sure about that?
I went with 0 after debug logging.
yes, the standard is 0 = left click, 1 = right click, 2 = middle click
I see.
Could you point me to some resources or something?
I am genuinely not sure where I'd even start with that tbh.
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.
well that's accurate, except for the left click
it just stays at 0 when I lmb
nope
as the documentation says, it's used for mouseup/mousedown events, not scrollwheel
it was probably just 0-initialized
so what's inaccurate about it then lmao
Actually, looking again at the code, I stand by what I said.
Wait, my bad, I think I see what's happening.
There's probably another bool or sm to check whether we got any mouse input this frame.
If yes, then we'd check the code.
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.
I see.
I chose to go with on scene gui since this bind should only work in the scene view.
Was that a bad choice?
What's Event? I thought it was unity api, but I don't see it in the docs...
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.
hm, i googled "event unity" and got this as the first result
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Event.html
I'll be fully honest, I don't know.
That part of the code was suggested by ai as I just wanted to get it to work as fast as possible at the time and didn't bother reading docs.
That's how we ended up here ig.
Yeah, for some reason I got unityevent results first and assumed that's the only thing.
ok, well thanks for the help
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
This was quite useful, thanks, this is how I solved it:
var e = Event.current;
if (e.type is EventType.MouseDown or EventType.MouseUp)
{
var isDown = e.type == EventType.MouseDown;
if (e.button == 1) _rmbPressed = isDown;
else if (e.button == 2) _mmbPressed = isDown;
}
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
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ah, that helps as well, thanks man
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
animation events
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
It depends on what you want to achieve. Apart from the method you've just mentioned, you can call specific events from animations at a specific frame, so you can execute logic very precisely
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
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
!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
https://dontasktoask.com ^ gonna need some info/context to be able to help
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
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
so u want to know the Animation Ended?
yes
https://www.youtube.com/watch?v=85kogmzcLXw
big info dump of ai informations
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
Make sure you are not confusing assignment = with comparison ==
Other than that you should post the code with the question.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
swear to the gods if that's the solve i'm gonna be mad at myself... i'll try that and if it doesn't work i'll post the code
thanks man, i got some UI done, but it's purely the scripting logic that is hard for me to understand, feels really overwhelming and uni is already stacked with assignments. I can't wrap my head around on how to make scripts interact with each other and how to avoid logic colliding, if that makes sense
I mean my does that and it's short but it's just icky that I can't figure out something more clean
our project is too ambitious for the time we got haha
why is u not clean waht u mean with that?
it feels like a crutch that's what I mean
also, there is this thing with Input Action manager and another way to do movement without it, which is better for a beginner?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
trying to fix it my bad
what is going on here if(collision = (gameObject.layer == 6))
@BlackHunter my englisch is chopped u need to explain the a little more so i understand u correlty
I just use basic input and remove Input System package because I do small games so fare and they don't need remapping/whatever
wtf
backticks
no this is the wrong sysmbol
literally copy them from the bot message
=> ``` <=
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
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
it's other way around, I realized that English speakers don't use the word crutch as a label for dirty hacky solutions
so yeah, what's going on there ^
trying to get it to recognize walls which have a specific layer
you're assigning a Collision2D to a bool?
if you want to check if it should collide, you don't need that collision = at all. just use the == in the conditional
neither of those work it gets mad with both
or better yet, set layer collisions properly so they don't collide if you don't want them to collide
yeah because that's not actually the issue here
Well, yess, because collision is not a boolean
collision = doesn't make sense at all
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
also you can just do this to avoid the magic number as well
im not a englisch Speaker, im from germany. im honest with u i dont really understand what the problem is, sorry my englisch skills are to bad
there's no c in English!
ok... so how would i do this properly because my instructor won't help me aside from throwing me a new shovel to dig myself deeper
my problem is "what I did is ugly, is there really no better solution!?"
what is ugly? u mean u code?
general solution
== 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
wrong guy btw
That should have been a reply to the other person, sorry
what
np really not that depp
u used Animation Event?
right to detect is the Animation done?
I used OnStateExit because it's more stable
dayumn i didnt know that this even exist, im new i thought u also are a begginer, i can send u how i did that and u can see if u maybe like that also, sorry i didnt really understand u corretly befor
but it looks bad, and using animation event would look bad, honestly, I am thinking if I should just use a timer
yeah i also dont like Animation Events
why do you not like anim events ?
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.
they didn't say that tho
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
yes, obvious missed word/ typo
every section I read about animation events screams that I should not use them for crucial logic
i also only use them for Logic
: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
Sorry
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
from Attacking to Movement u also can just use a "Has Exit Time" => 1
Dont care about look of code in that respect.. care about functionality and move on
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
I was doing that and I was ending up under piles of spaghetties
you've gone too far
I got exit time 1 on repeat and on going away from attacking
yeah it repeats attacking instead of going to moving after each attack if player is in range
so u mean? the Enemy is Attacking conistently?
and u dont want to reapeat the Attack Animation?
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...
What calls the attack in the first place?
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
u will but probobly not the best from me tbh
but i want to help u
Manual is your friend. Investigate what is involved in the code and check what members have the objects you are using. You are accessing https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Collision2D.html so look how to access gameObject involved in it, then compare its layer to the one you need. Also examine how to use layers in the manual.
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
what game are u making a 2d Game or 3D?
how long do u devolop Games?
longer than I would want to
till you realize you can do anything but it's years of tedious work
make a small game
i also do one
or do u mean to have the needed skills for a commectial game?
it's not about commercial it's about general size and pool of content and mechanics
making something big - ton of tedious work
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!
the personal problem is better I know that I can do stuff less interesting it is to do stuff
wait so lose u motivation if u know that u can make stuff?
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
I never said I was good tho
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
ohhhh... i know exactly this feeling..
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
can anyone tell me how can a Vector3, in this case transform.up be equal to a vector2 type object called direction
it'll just auto put z as 0
would it happen the other way around?
as in if there were a vector2 object and i wanted it to copy the values of a vector3
a vector3 into a vector2? I presume it would ignore z.. but dunno, try it and see
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 :)
well for (1) i see two colliders there..
If you're using a rigidbody, don't move with transform.position
for (2) use the rotational constraints on the rigidbody you can lock individual axis
Dynamic and Kinematic Rigidbody have different rules for how to be moved / rotated, to preserve interpolation & simulation accuracy
def get rid of that extra collider whatever route u decide to take
Thanks everyone, I'll try to fix the problem :)
unless its a trigger or something
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
Sorry you have both a cc and rigidbody?
oops
Is invoke just the odd child of calling a function but it got an haircut and can't call functions with paramaters?
the monobehaviour one ? yes its the ugly ducklin
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
Oh, i absolutely love using coroutines

lol, but you just made me realize how redounded invoke actually is
shhhh, not you unityevent invoke. You're useful.

the OG Delegate invoke the handy one
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?
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
in update like it says
even tho thats pretty cringe
it says after addforce though
yes after the AddForce. Under the }
this way it corrects any values AFTER addforce was added
wouldn't you want it to be correct before it reaches that state though?
or is it for the next loop
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
15.1 will be corrected right after
i can't type
isn't accumulated force only applied to velocity upon fixedupdate
so what does that mean?
Idk why unity wants to put this in update
also isn't there a maxVelocity
but I guess it applies it and then by the physics frame is ready
can i tell you guys how i would do this?
and you tell me if that's an aight approach or not
ops misread that
huh yeah wouldn't maxSpeed be more technically correct...
ya cause its multiplied with normalized so its always gonna be maxSpeed
same thing as doing linearVelocity = Vector3.ClampMagnitude(current, maxSpeed)
do whatever the tutorial tells you 😛
normally .velocity / addforce do belong in FixedUpdate so idk
what the tutorial is saying doesn't make sense to me, i hoped that by asking here, i would understand...
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?
!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.
like i can blindly follow the tutorial but then, i won't understand what i am doing
by the next physics tick / game frame you're gonna have the corrected value, then you try to go over, gets corrected again
that's what i was saying though
its happening so fast practically unnoticeable
thx for the confirmation still
its basically, why would you add it in the beginning of the frame because then you will have "overflow" value before getting it corrected
does it rly matter though?
like 14.9 vs 15.1 doesn't seem to be a lot of diff
imo
maybe not always but depends how the tick / frame happened
i always assume its best doing it before the frame ends is best
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 
@naive pawn whats the main difference between new and old and which is more beginner friendly?
I switched to the old one
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
ah, okay i'll use the old one for now
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
alright
This is what I mean.
a simple use of new input system
[SerializeField] InputActionReference moveInputAction
Vector2 moveInput
Update(){
moveInput = moveInputAction.action.ReadValue<Vector2>();
transform.Translate(moveInput * speed)
example in the context of a character controller
https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
what in the, i made the movement script, but directions are off, might be the camera tho
Hey
lemme just rotate it quick
yeah you don't have to lead with this, just ask your question straight-up
saves us all a little time
you need to make it relative to your camera plane yes
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?
bro i just said hey
dayumn
yeah, it was unnecessary
subtract new position from old position and check the distance ?
check the magnitude of the input? im confused, are you trying to implement or counteract a deadzone
like, i want to detect => "Is the player moving, more than 0.1f?"
ya or magnitude of character velocity works too
what is the Syntax of it? can u pls show it to me
eg
if(player.velocity.magnitude > 0.01) //is moving
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
always best to use square magnitude though as its faster
does my Player requiere somthing? like Rigidbody?
character controller or rigidbody
what exactlly is that`? and why is it faster?
how do i stop this madness from happening? i am pressing space...
press the insert key
it skips having to do a square root which can save some calculation time, but in most cases it doesnt matter
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.?
Thanks for the explanaction!.
you could do that sure, depends
if you only want to count as moving with keypresses / inputs then go for that
okay, know i know everthing i need. Thanks Nav and Chris
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
cool, we aren't psychic though. what's the error, and which line
alright, you have something wrong above that
wasn't showing these errors prevouisly though
you missed a { or }somewhere
here's a hint: you can't declare public members inside of a method
oh goodcatch how did I miss that in the screenshot
it's in their video when they were struggling with the insert key
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)
then what's this abt
you put public float ... in the wrong place
public float maxspd = 15f;
perhaps it should've been clearer in the instructions but this should be A FIELD not a local variable
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
give an example
like what can be done and what cant
public float fieldValue
void Method(){
float localValue
public float anotherValue // error , we cannot have access modifiers here
}```
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
so basically, since the local variable only exists inside the method temporarily, i can't access it...is that the gist of waht you are implying?
it can only be accessed within that method yes, so access modifiers are not needed.
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.
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
Thanks! it was easier than I thought lol
worked out
like this?
Func<Awaitable> doSomethingLater = async () =>
{
await Awaitable.WaitForSecondsAsync(1f);
Debug.Log("Lambda finished!");
};
should work
await doSomethingLater();
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
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
hm, interesting info. thanks!
I suppose they like really similar to Tasks, so I'm overthinking it, hehe
i need the blocks to be able to be moved around freely but collide and slide
yeah I think they tried their best to be as closest possible to task so not to cause friction in usage
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)
maybe try using Rigidbody.Cast (2d)/ Rigidbody.SweepTest (3d)
youd' manually need to detect it and prevent movement manually
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);
}
}
I'm trying to achieve something similar. just background processing here and there for some calculations/loading, nothing special. I like that async context can be switched to the main thread by Awaitables API methods, kinda neat thing ngl.
yeah exactly thats the main selling point for me
get rid of * Time.fixedDeltaTime
AddForce is already moving on Tick fixed Delta
you're essentially adding it twice
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?
are you looking for a paralax effect?
YEAH! this is what i search better said
is my thought correct? better said my plan?
what do u think?
ah okay ill look into that
just look for paralax tutorials it is easy to achive.
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
isnt it just different backgrounds at different speeds, in its most simplest form
so i dont even need to lerp somthing?
the z axis is your friend
I dont think
nice, i will try it looks easy to me
some like Movespeeds
background_back = 3f
background_mid = 5f
background_foreground =7f
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?
i want this booster to appear only when i left click, but it does not appear when i click it
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.
because Update doesnt run on Disabled GameObject
it says to make it inactive though...
the script Player should be on gameobject Player, not on the booster
still not working...
show the setup
i posted it
yes but thats the old , show what you changed
and the Player script?
on Player object
post the whole thing?
not the code, uncollapse the Player component
then?
screenshot
hhuh
i was gonna ask, how does the pc know that the booster is the game object
lol uncollapsing it has no effect , i just wanted to see the reference was assigned
i did not
i assigned it after you asked
was wondering this then saw it not assigned
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
mhm yeah thats why assignment is important
u also can use Error Pause, so its frezzes the Game if u have a null reference
the guide told me to use this layout...
ya that too, but i don't have the console window visible so....
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
if u have Error Pause u dont even need to open the Console Window
but its better if u check it out if u start the game
I mean you still wanna keep the console there open at all times
thats your lifeline to the "backend"
thing is, i can't get it to work the way the other tabs do
yeah but then its not open at all times especially with Project view
best to keep it there
eg hers mine
i'm on a 13 inch macbook
what game are u making?
this ain't massive
nothing rn just testing random crap
trying to finish this I started a few months back
nice
Fire On God
Its very retro
the mouse showing is a bit eee though
ya it was a 1 bit jam but ended up missing out on the deadline so Im gonna make it a smaller game
i remember wizard legends using a similar thing, didnot like it
debug mostly
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?
as long as the winding direction is correct it does not matter
and that part is done in the trinagle array anyways
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
show the code that caused it
also you do not want to be using the UnityEditor namespace in your game logic code
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.
yeah builds will fail if UnityEditor namesapce is used in logic that makes it into the build
its only around while in editor
Unity basically strips those when you build
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
stupid question, is there a way to look at a transform or collider of an object while moving another object in scene view?
can change one of thse options to give it a icon or show a name in scene
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
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
but I need to move the other object via the transform arrows.
The handles will appear on whatever object is actually selected.
alt shift p also pops out a locked version of the inspector for the selected object
ooh, handy!
Changed my whole unity experience when I learned this 🤣
sorry, I didn't mean inspector, I wanna look at it's collider or transform arrows in the scene view
Guess I can just open up another scene view
oh wait,
I can do it the other way round
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?
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
That sounds like a job for a particle system!
Very bad yes
.... i have sprites of the leaves....
A particle system is what is usually used for this kind of thing
Perfect
Yeah, probably
It'd be weird if you didn't
I’ve done leaves with meshes as well
if i use a particle effect, would that also allow to animatie the leaves?
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
with the write sheet layout you can even randomly choose a row and animate across it over lifetime
and what would be the dirffrence? between a normal Animatiatead leaves and a Particle System Animated leave
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
particle system is greatly more effecient and can do huge numbers of that at little cost
e.g. wind, collision with surfaces, fadingi n and out
and isntead of hand animating you can apply forces and noise
they're incredibly useful (i mostly work in VRChat right now, and you can pull off a ton of stuff without any scripting)
Thanks i will try it
in almost all engines its like the stadard way to handle, smoke, sparks, leaves, dust, rain, snow etc
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?
im using continuous
heres my code:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
super messy code right now but im just trying to get the functionality working
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
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/
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
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
my Goal is to make a Scalable Combat System for a 1-3 Month Game.
To get a smooth scaling effect, you need to do exponential scaling – the rate of change is proportional to the current size
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
I see, in the past I have created similar effects in Blender (https://www.youtube.com/shorts/S15PC1Itmw8), though I'm not sure if this is different where the walls spawning at the center seem to grow really rapidly, kinda like a pinch filter. I assume an effect like this would need to go on the verts rather than the entire gameObject's scale, moving verts closer to 0 0 0?
(and then stop growing, because lerp is clamped)
This seems to show the tin on the left totally warping like a central vanishing point drawing
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
Ah interesting, yeah. So I would create a shader for some GameObject that adds walls and floors on a simple exponential scale/zoom, then warp the center of the object with shaders? I'm sorry, lack of knowledge for implementation of the two combined here
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
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!
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
Sounds like it actually isn't as hard as I expected, tysm, I'll give it a go
no prob (:
how do i get the main parent of a gameobject
.transform.parent
but that gets the parent of the object, i want the main parent even if its being held by multiple parents
transform.root
i cant believe i have just found out this exist 😔
actually fixes all my problems ✌️
Ah, wasn't sure what you meant by "main parent". Yeah that's root
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
?can sombody help me there?
bist du deutscher?
ja bro
nice
hahah endlich mal einen deutschen getroffen hah
was würdest du mir als tipps geben?
will unbeding besser werden auf ernst atp
English only #📖┃code-of-conduct
sorry, i said to him, "Can u pls rate my Code and give me some Tipps, i want to be a better Coder"
for starters don't suffix your script instances with 'ScriptRef'. Lots of magic numbers in your Update method, why 0.22 and 0.27? Define them somewhere so they have a name.
And a lot of stuff in a single script. Shooting and Melee should probably be in two separate scripts.
what is a megic number?
okay i will try to have to make them in seperate Scripts. Thank u bro!!!!
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;
ahhhh yes i already habe this, in the Variabels u can see "useOptionalTimers"
so i can defint the float values if i want
looks great and very clean!
bro wir müssen englisch reden. Thanks bro, try to improve my Skills.
what is causing this to happen? None of the errors take me to a specific block of code
known editor bug, deselect and re select and pray it works.
update your editor to fix it (should be fixed now)
do not do that, just update to the latest 6.0 version
downgrading major version will probably fuck your whole project
ah I see
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
!learn
for me what worked the best was doing the official unity course
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this
oh and it is free, thank you very much guys!
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?
sure, just provide the necessary information when you !ask the question for others to help . . .
might need to elaborate on what "whoever wants them" and "everyone" is in this context
How do I connect visual studio to Unity? Unity classes are not highlighted
Do you mean which application you want your scripts to be opened in to be vs?
it should be in settings > preferences
but i dont have it open rn so i cant see if that's correct..
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
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!
I know android doesn't support both so its unwise to want this (unless this is for specific platforms you know support both). You can use conditional compilation to support both input systems.
I'm developing for windows for now, so that should be fine 🙂
Someone tried to install my package and it didn't work because their unity client had it by default as the old input system. What's weirder is that he had to restart 2 times after changing the setting to "both" for it to take effect. That's why I would like to change it automatically if possible!
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
you can use conditional compilation to check if the new input system is enabled (#if ENABLE_INPUT_SYSTEM), and if it isn't, prompt the user to change it i imagine
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?
Okay, thanks!
I think I will try this then. If it cannot be changed automatically, I will make a prompt to tell the user to change it himself. Thanks for the snippet, that will come handy!
you can probably also add a button to open the player settings window if you're fancy
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.");
}
yeah that should work
cant wait for most things to ditch the old system
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
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"
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
That's true!
I think it's about time to use only the new input system
definitely yeah
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?
i never had to?
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?
that's not the package itself, it's juwst some resources that tmpro needs to be in your project
True
probably so you don't have extra stuff clogging it up if you don't wanna use tmpro (ui toolkit or legacy text)
yeah it's a legacy thing
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
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)
legacy compatibility i imagine
so that if you're migrating an old project that doesn't use it it doesn't just break completely
That makes sense
but tmpro is the one that should be used
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)
Its somehow not functionality offered by the splines package
what isn't? (just asking)
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
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
The spline package sample Extrude Spline and Nearest Point seems to do that by using a separate spline for the profile and extruding that along other spline. That is probably not optimal but should get a rail done
hmm yea that sounds like a decent option 🤔
This is a code channel. Delete and ask in #📲┃ui-ux -> with screenshots of your setup
ok
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
Debug.Log to see if the latter is running at the beginning of the game
It's a little odd though - which script is each of these snippets from and which object is that script attached to?
void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
Instantiate(ExplosionEffect, transform.position, transform.rotation);
RestartButton.style.display = DisplayStyle.Flex;
Debug.Log("Restart Button is Displaying.");
}```
Like this?
oh wait
i don't think that's the problem, cus the explosion effect doesn't play unless a collision occurs
Check anyway
Ok so back to this question
lemme check
Because from that error it looks like you don't have a valid reference set up
the script is the PlayerController script and the object it's attached to is the Player
u only want to kill the player if he is colliders with the rocks?
yes
if yes u should also make sure that u only allow collisions with spezifical Objects
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
did u maked sure that the Ui is visible to false befor the game starts?
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.
under the player have this colliders?
well, i am not really in a position rn to tinker with stuff the tutorial told me to do
once i get through this, i will do that
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?
yes
yes or no?
rb? is rigidbody2d
``Rigidbody2D rb;
imo that's a really bad mentality actually - you should tinker with stuff tutorials tell you to do - that's how you learn
i mean "Collider"
if u child has some Colliders => "u player collides with them and this run the trigger methode"
nah, i don't think i have it rn
these are the basics i am learning though, i don't wanna end up adding smth and then stop the code from working altogether
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
what should i look for?
yes you do, you'll learn much more if you do that
the goal of a (gamedev) tutorial is not to get a game out of it, it's to learn how to make games yourself
look under u players child object and just make sure.. have the objects a collider?
wait a sec
i set up the is trigger to true in the inspector window for the three objects
they do have a collider otherwise it would not be exploding rn when colliding with stuff
yeah but i think if u have the child objects a collider and "isTrigger" is setted to true u trigger event runs
i wish i had better englisch skils, i think i would understand everthing better.
can you give me an example for it...
it's also possible that i am the problem
nahh bro
bruh i am new tooo...
what's the trigger event?
yes i did do that
okay
u code is thinking i "Collides with my self" so i need to use my Trigger code and make Ui visible
ok...
IM NOT SURE, im really not the best but u need to make sure that u only allow collision with spezifical objects
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...
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....
theres collision matrix to exclude collider collide in different layers
or the include exclude box in the collider component
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
so basically, you want to check for whether the object has a certain string in it, in this case "Rocks", and if it does, the collision occurs?
its the same as you doing if(tag) then execute
i ain't colliding with myself...
the game runs, problem is the restart button ain't working
but u had child that has a collider and a trigger??
they did not have trigger
oh
this your player? every child has a collider?
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
i did not have the trigger enabled xD
good
are the child overlap themself ?
so u only problem is that u restart button are not working?
meaning?
what is not working`?
it appears at the start, not when i collide
triangle or square there in your player, are ther collider touch each other, if yes then your player is colliding with itself
AND u are 100% sure that now any of u child has a trigger AND istrigger is false
this is what i try to explain, but my englisch skills are hella chopped
idk brother same
looks fine to me
the restart ain't fine
where is u ui gameobjects?
better said what controlls u ui?
what Script controlls u UI*
are you asking for the script?
yeah
this also controlls the restart button right?
yes
the code inside the script?
yes
i mean can you show it
should i post it?
maybe u coded somthing wrong can u post it
brother yes pls
this
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
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this happens when i comment the whole thing out
how is it still showing up
well you see, its already show up
exactly
its not about the collision
yes...where did i go wrong
your reference is wrong maybe then
RestartButton = UIdoc.rootVisualElement.Q<Button>("RestartButton"); this thing?
it does print null when i collide...
check your naming and stuff
yes, it does show null reference error
prolly naming problem
That’s ur problem
What’s the null ref
click there two time and see to what lines it brings u up
u didnt assing somthing
its the button
Player
defintely
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
private Button restartButton; it's private
i can't access it through player
it doesn't show restartButton in the list
Add a [SerializeField] on top to access it from the inspector
you said this thing is null, that means this line here fail to get the refernce
check if the right side thing correct
s1nth
what name should the thing inside " " have
idk havent done UITK before, did you not know what to put in there in the first place...
try rewatch the guide you follow
me too
RestartButton = UIdoc.rootVisualElement.Q<Button>("RestartButton"); just tell me what name is the "RestartButton" supposed to refer to?
what ever name in your ui doc
where is that at?
... please rewatch and understand the guide you follow
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
type shi

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...
So like the ship explodes and the asteroids keep going?
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
Wdym “a bunch of collisions” don’t they only collide with the player?
they collide with each other and the boundary
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
Make an on collision enter 2d for the asteroids and decrease their linear velocity when there’s a collision, or you can use physics
i will try it then
The other option is to make a physics material with a bounce of LOWER than 1
Which is prolly simpler tbh
I’d do the physics material
lower than 1 or more than 1
Lower
in the interent u can see other people solve this provblem with code
but its very hard, they use a mathimatical way
my bad sorry, i thought u need to make it heigher
i don't want the collisions to die out
{
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 🥀
Wait what? You said you wanted the asteroids to slow down and eventually stop when they collide
no..i said that that's what it happening
i don't want that to happen
no he mean that if they collides (the rocks they never stop moving) and lose the energy
i think...
Oh in that case make a physics material with a bounciness of exactly 1
bro, those are conservation of linear momentum formulas in code
🥀
what
oof
is that not default?
i think it's this formula that they are trying to replicate using code
Helllll nahhh bro forget to asing a value but know this shit
No
the variable names match
🥀
That’s really unecessary, unitys physics does it for you
ya, that's what i think too
yeah he is definetly right, the code looks also very hard to understand. for me tbh
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
how about you try coding it out, it won't look that bad. the formula isn't that hard to understand tbh
ofc, you wouldn't be using it but u know, if it fascinates you...give it a shot
definetly
and im 100% i will need that in the Game Devolopment in the future
for nice levels i think
S1nth?
are u also new?
yes
i mean...kinda depends on what you call new. i am new compared to most people in here soo....
normal.normalized
HAHAHAHA
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?
public string this[int index] ???
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
So wait what are you trying to do? Initialize the array when you declare it?
No
Sorry I don't understand
Yeah, I guess that is what I'm trying to do
this is an indexer to refer to its class as an array.
private string[] cubeState **= **{ "one", "two", "two", "one", "two", "two", "one", "two", "one", "one", "two", "one", "two", "one", "one", "two" };
you forgot the =
if you just want an array with certain values
I didn't understand the question lol
i think he's trying to initialize an array with values
oh...so it does work! Yep, that I wanted. I
I could have swore I tried that and got errors. Thank you!
np mate
For your question...none of the Monobehavior methods work for initialization? Awake() or Start()?
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
The only alternative is to have your own shell over the component system.
Or a method that accepts generic interfaces
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,
But to be honest, the need for Inits methods is not even a problem.
why?
How would you solve instantiating prefabs / adding components with different values?
@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
Init is already a solution to the problem, and MonoBehaviour's lack of constructors is simply the need for an engine to use serialization.
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
kinda agree, just need to be careful not to forget to call it, lest you have errors.
Just from a testability / implicit knowledge POV.
But yes, they do solve the problem
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;
}
}
StartCoroutine returns Coroutine handle use it or call StopAllCoroutines
Use an interface, it'll require you to have an Init method . . .
Yeah, i used StopAllCoroutines, but why doesn't stopCoroutine work?
It heed coroutine handle
You mean the Keyword Coroutine?
Which is returned by StartCoroutine
yes
So something like this?
Yes
yeah. not used to using that. i need to learn it
thanks for the help
also fumo.
🫳
I meant forcing the creator to call init() / having it part of the argument.
Not interfacing the definition of Init()
(unless i misunderstood what you meant)
If you have more than one instance of the coroutine running, it doesn't know which one to stop. By using a Coroutine handle, you are telling it specifically which coroutine you want to stop . . .
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?
Use tags
i don't know what they are, got a guide?