#💻┃code-beginner
1 messages · Page 197 of 1
The main camera is on the second screen, the first one, which is the menu, does not have a camera and is working normally, which I find strange
Is your main menu an overlay canvas? You wouldn't be able to see anything behind the overlay, but you do still need a camera to render the overlay on
Adding a camera to your menu scene means it can now properly draw the overlay, which is over everything
You want to either unload the Menu scene when you change scenes, or disable the canvas
Pretty sure there is something. Did you check the documentation?
I didn't understand
I did check for animation, which just leads you to the overall animation tab which is not very usefull and the animationClip, which doesn't show any usefull command, it just to store data it seems
public void jogar()
{
SceneManager.LoadScene(nomeDoLevelDeJogo);
}
when i press "Jogar"
Wdym "leads to the overall animation tab"..? What the heck were you looking at?
It looks like your menu is being drawn over the second scene. Assuming your screenshot earlier was showing that both scenes are loaded at the same time
I was referring to the API docs, not the manual.
I did check that, I don't think any of those does what I want
Of the Animation class...
You are the one who brought up the animation component, so do check it's documentation properly.
Oh, yeah, that's what I was doing wrong
I see it now, thx
I was using just animationClip for it for some reason
well Move would does its things for 1 frame, and its not a good tool for this
unless thats your own move method, in which it depends in its implmentation
also syntax error in your code, you are missing a character and your editor is trying to point it out to you there in red
Hard time closing the if condition with a bracket?
are animation parameters exclusive to the gameobject with the animations or can i use the same one on a different gameobject
Wdym? The parameter names are the same for every animator that uses the same animator controller. The values are obviously separate.
what? im sorry im a newbie
oh right thanks
Was referring to the error in your code.
yeah
yeah
Am i allowed to send my code here to get help?
Yes, if you share it properly.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
can i just send a screenshot?
Unless there is a specific reason it has to be a screenshot, no.
okay
a screenshot makes it harder for people to help, since they cant search it or copy and paste
this made my object jump
thanks for the tips also
https://paste.ofcode.org/6YFrtcSWm8t4LPJKiPAFZA For some reason, no matter what country i put in the debug log, it's always printing "SouthAmerica" and "Europe"
Basically, in my scene i just have 6 tiles and im trying to store which tiles are adjacent to each other and they all have appropriate tags (e.g the top left tile is north america etc)
Okay, but shaders do not have inheritance or anything. Like there’s no base shader i could modify to make this work. Wouldnt i have to also edit the Tmp shaders to achieve this aswell?
Yes and yes.
@teal viper you can just
and not say why your 
most would copy and paste and modify, or use includes in the shader to grab already defined functions from elsewhere for things
We just had a conversation about not sharing code as screenshots and you ignored it completely.
oh im sorry I didnt sorry my b
I should I share code
can someone take a lil look at my code potentially pls 🥹 👉 👈
If your problem is fixed, you don't need to share anything, but do check the bot message for future reference.
You posted it 4 minutes ago ...
oh crap
yus that one : )
my bad guys
I know. I'm saying be patient
will do in the future tho
oh mb sorry
Show the inspectors for a few of the objects with Territory on them
Maybe a good first step would be doing it with 2 simple ui images overlapping using the default ui shader
But I’ve looked at tmp shaders before and there’s no way I’d ever figure this out for those
Without breaking something
So it’s hard to be motivated
@summer stump
i dont wanna clog up the chat with screenshots so theres 2
and the rest just have tags like "Europe" or "Asia" etc
If these are prefabs, why use FindWithTag?
It looks like the tags are set right though
idk i literally downladed unity yesterday and im tryina get the hang of it
if theres a better way of doing what im trying to do then i could do that?
Well, you want that feature, so it's all up to you. On the other hand, no one forces you. If you want to give up on it, it's your choice.🤷♂️
i still dont get why my code doesnt work tho
Ah ok.
!learn is a good course (a bot will pop up)
But I recommend just dragging the prefabs into the inspector
See serialized references here
https://unity.huh.how/references
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
guys i was following with brackeys tutorial on unity 2d games and i faced an issue with the collider being rapidly enabled and disalbed on its own ,i told someone on the #💻┃unity-talk and he said to share my code here so hopefully someone can help me,
here is the movement script i made:
using UnityEditor;
using UnityEngine;
public class movement : MonoBehaviour
{
public CharacterController2D ctrl;
[Range (0f,100f)]
public float speed = 40f;
float horizontal = 0f;
bool jump=false;
bool crouch = false;
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal")*speed;
if(Input.GetButtonDown("Jump")){
jump = true;
}
if(Input.GetButtonDown("Crouch")){
crouch=true;Debug.Log("c");
}
else if(Input.GetButtonUp("Crouch")){
crouch=false;Debug.Log("!c");
}
}
void FixedUpdate(){
ctrl.Move(horizontal*Time.fixedDeltaTime,false,jump);
jump = false;
}
}
and here is the 2d controller brakceys provided:
And I mean, the debug prints from the findalltags("Europe") part
!code 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
wdym @summer stump
huh?
pretty self explanatory
sorry im new here
Debug.Log(GameObject.FindWithTag("Europe").GetComponent<Territory>().adjacentCountries[0].gameObject.tag);
Debug.Log(GameObject.FindWithTag("Europe").GetComponent<Territory>().adjacentCountries[1].gameObject.tag);
This is what prints
So, just the two adjacent to Europe
yes
yes thats what i want it to print. but it doesnt print that
it prints the two that are adjacent to South america
can please someone help me , chatgpt and google bard can solve it for some reason
And Idk why, but the first thing that i tested it with was south america, so that might be why?
Trying to figure out how to give my jump a range like my runspeed https://hastebin.com/share/afehuhixuq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Share code properly. You were pointed to the bot message.
It's doing it in OnValidate, and using find, so I am not sure what's going on. Could be printing at odd times
MissingReferenceException: The object of type 'PlaceableObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Props.DestroyableObject+<>c__DisplayClass4_0.<DestroySelf>b__0 (System.Int32 _) (at Assets/Scripts/Props/DestroyableObject.cs:37)
Why do I get this error on line 37, if the object is destroyed after that?
PlaceableObject Script:
private void DestroySelf()
{
foreach (var drop in _drops)
{
if (!Chance.Of(drop.Chance)) continue;
var amount = Random.Range(drop.MinAmount, drop.MaxAmount);
Enumerable
.Range(0, amount)
.ToList()
.ForEach(_ => ItemDropService.Instance.DropFrom( // <--- LINE 37
transform.position,
PlayerMovement.Instance.GetFacingDirection(),
drop.Item)
);
}
if (!_destroyOnDeath) return;
UnregisterSelf();
Destroy(gameObject);
}
Trying to access an object that was already destroyed. Hard to say anything else from just that snippet.
Though the fact that it's a PlaceableObject should give some clues.
Destroy isn't instant
The debug logs print 6 times collectively (once for each country) but its saying the same thing for each country, when it should be different for each country because each country has different adjacents
I dunno. I feel like the fact that it's using OnValidate and Find are the issues, but I am not sure
They all print the contents of the same object though. The one with Europe tag. Unless I missed something...
nono but they dont. they all print the adjacents to the "North America" object
Yeah, they want that, but think the Europe one should only have Africa, North America, and Asia
when it should be the adjacents to the europe one
Take a screenshot of the Territory component on an object with the Europe tag.
alright so once again but with code share as needed:
guys i was following with brackeys tutorial on unity 2d games and i faced an issue with the collider being rapidly enabled and disalbed on its own ,i told someone on the unity-talk and he said to share my code here so hopefully someone can help me,
here is the movement script i made:
https://gdl.space/nepawutuka.cs
and here is the contolller brackeys made:
https://gdl.space/zucudutepu.cpp
please help i have no idea whats going on
Is the adjacentCountries field not serialized? Make it serialized or enable inspector debug mode.
Make the field public
it is
They are properties
You need [field: SerializeField]
Edit: yeah, that's it
i just slap that before the adjacent countries field?
Yep
Line above, or same line before the rest of the code
[field: SerializeField] public List<Transform> adjacentCountries { get; set; } ?
like this
You probably missed something in the tutorial. Rewatch it and make sure you follow line to line and that your scene setup is the same.
If you really need help, start from providing more info on the issue. Like a video of the issue.
Nothing in the code you shared referenced the collider or the active state of anything
im pretty sure i did everything as shown ,but ill check again
okay its a step in the right direction, but now my code prints this (i changed the Country in the debug log to Asia)
what do you mean?i have two colliders for the player one circle for the lower part of the body and a box collider for the upper half wich is supposed to get disabled when crouching , but it disables and enables on its own
Ok, show THAT code
Because it doesn't do any of that in the one you shared
i showd both didnt i ?
You said one you made and one brackeys made
yea
Do you mean the bottom one is one you have
I assumed it was just what they wrote and you werent using it
no the complex one was made by brackeys(the 2d controller)
the other one i made (the movement one wich look simple)
Ok, looked through that one and still dont see anything setting colliders inactive
Can you give a line number?
Honestly, that code is rough though
Good evening - I'm curious, whenever I see tutorials about Scriptable Objects, it always seems to include setting a Menu item for creation of the object. Is this part necessary for Scriptable Objects to work? just seems a little too coincidental that all videos I see, it's included. Thanks!
It is not necessary, but it makes them much easier
cool, thanks @summer stump
They are asset files, so you will generally want multiple of them, otherwise why even use an SO?
ik he said it usually is and there is no need to learn how make one myself and to just downlaod a ready to use controller all the time ,
oh wait @summer stump i just realised that what you said completely fixed it im pretty sure, so thank you for your help. Can you just explain to me what [Serialize field] means and what it does so i know for next time
there is a attribute you can add to the top of the class to make this menu item for you
as for the line i have no idea what line could be causing the issue since there is no actual errors
but if its not needed and you want to create them via your own logic its not required
Serializing makes it so you can see the values in the inspector
Well, nothing about your issue is an error
I just think none of that code is relevant to the issue
so what do i do im rally confused
ok thank you
Find wherever SetActive is in your code?
Im still dealing with this movement state machine issue. how can i reference the rigidbody.velocity from the rb component of the player onto the PlayerIdleState? Any way that I know of trying gives me a null reference error during runtime. https://paste.ofcode.org/8NfSyqskSeXqAxiREAu2bY Edit: I replaced the parts that give errors with Input.GetAxis(Keycode)
Start from explaining your issue properly. We're still not sure we even understand it correctly.
Recording a video would be better if you can't explain it in words properly.
What lines gives off null reference?
alright,so im following up with brackeys tutorials and got to the part where i learn about movement , he said it was best to give the player 2 separate colliders and disable the top one to crouch , a circle one for the lower part of the body and a square one for the upper part which is supposed to be disabled when i want to crouch ,however the box collider is rapidly being disabled and enabled on its own without any relalted input which causes the player to get jittery when trying to move against a wall or so /
hopefully htis was a bit clearer
{
Debug.Log("Help! I hope you see me!");
if (playerMovement.rb.velocity > Vector3.zero)
{
player.SwitchState(player.WalkState);
}
}
I tried using PlayerMovement playerMovement;
the if statement throws an error, i tried GetComponent<Rigidbody>()
Can you record a video demonstrating the collider being disabled and enabled?
ill try
Where do you assign playerMovement?
on the PlayerMovement script
*where do you assign the variable in this class?
This happens when i use the method playerMovement.RigidbodyMovement(walkSpeed) too
should i assign it to a vector3 variable? since im using position?
Let's start from basics. Do you understand what a reference type is?
yea a variable holds the data and a reference type points to the data
theres probably better wording but yea
A variable holds data?
So, a variable can't be of a reference type?
What does this line in your script do?
[SerializeField] PlayerMovement playerMovement;
i figured it allowed this script to see the other script, or use a copy of it
No.
What is that line called?
What are you doing on it? Is it a declaration? A definition? Initialization?
uhh not sure, probably initialize?
No.
ooo so close
It's a declaration. What does a declaration mean?
Did you go through this stuff? It's all C# basics, that you should go over before even touching the code.
here is the video
lol im pretty well adapt to coding, im just not great at it
im just getting stumped with one part of it lol
Then you should be able to tell me what a declaration and initialization are. And how they are different.
This is more correct if you replace "variable" with "variable of value type"
okay, ill figure this out on my own. I figured if i knew what the answer was i can work back and see what i did wrong more clearly. I get your super smart but i dont need a lesson man i can teach myself
To go back to reference types.
References are also data... that references another data.
Every time you access something through a reference type, you're indirectly accessing the data in the reference.
value type is everytime you pass it somewhere you copy it, refernece type is you just copy and pass its address so the other thing knows where to access it
Here's the code that enables/disabled the collider:
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
} else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
If it enables/disables rapidly, it means that the conditions are changing every frame or so. Check what conditions are changing and why. Use logs or the debugger to figure it out.
Well, we told you multiple times to go through these basics, and yet you're still here with the same question, which makes me think that your "self teaching" is not done in a correct way.
i spent a day or two going over unity basics, and before this i spent a month or so in it, i mean its not hard to not understand something here or there, If i was able to make it from not knowing how to move a character to the new input system and then now statemachines with a couple minigames under my belt, i mean, i feel like i got farther than go back to square 1
We're talking about code here. About how C# works. This has nothing to do with unity or character movement.
Or input system.
Or state machines.
What you miss is exactly the square one.
And you try to build something on that missing square. Obviously it's gonna collapse.
okay, sorry. Ill figure it out.
Reference types or simply referred to as just objects is very integral part of game development (objects as in a character, a character's limbs, and even abstract concepts are objects). So it's gonna be helpful to know it.
I think that's also an issue. It seems like you try to figure something out on your own, but eventually get a wrong understanding. Then come back here after it's not working. Instead of repeating that loop, maybe try back up your understanding by asking here wether you get it correctly.
i just want to point out that in an object oriented language like c# where everything is an object, implying that just reference types are objects is incorrect
structs, which are value types are also objects in c#
because everything is an object in c#
Oh yeah.
which you choose really depends on its purpose and how big it is
It's best to break something down.
And have one manager class to manage them.
C# does the value vs reference type thign with structs vs classes, other languages just let you choose on the go wether you pass it via a pointer or directly
i think the biggest misconception i've heard is that value types exist on the stack and reference types exist on the heap . . .
Certainly yes.
references almost always end up in heaps, for value types its every devs favioute phrase
"it depends"
Well I think "if it's inside the function, a struct is on the stack" will suffice.
before worrying about performance and if its heap and stack you should think about how you are using the data and which is more suited
that depends, is the struct a local variable or a class variable?
also even in cases where its on the heap anyways like its a member of a array or list, structs can still help things along
Ok, declared inside a function.
since instead of a array of references to things elsewhere in memory, you get a array to just the thing you want
but would always choose first based on how its used and if you want the shared mutablity or not
value types are only stored on the stack when declared as a local variable or a method parameter . . .
also even as a local var are some cases that make it escape and end up on the heap
I don't think indirection like this is that costly.
why talk about stack and heap here, its a managed language lol
How?
just making it more complicated for the person who is learning..
this is important for performance and gc allocation . . .
also the bigger message i am trying to get along anyways is choose mostly based on if you want shared mutability or not, and if you want to compare it based on value or identity
boxing a value type is one way to allocate it on the heap. or if the compiler determines the lifetime of the variable exceeds whatever expected time to be on the stack would be. there's actually a few ways to get a value type on the heap.
I wish i could find the really in depth article i read a few years ago about GC and struct allocations 
Oh you meant it like that.
I was imagining some breaking way to make a stack memory leak somehow.
its really something not to get indepth about unless you are having issues iwth allocations and gc
use what is best suited to your logic and has the most clear intent
if there are issues a perf wise profile and learn why
yeah, if you're boxing value types intentionally, then shame on you . . .
Yeah I always avoid boxing.
it happens easily, interfaces
I use generics in this case.
Should I consider implementing an interface specifically for ID, or perhaps I should generalize it a bit more between assets? Maybe have a ISerializeID which extends into IItemID and IProfileID that are just naked interfaces
i don't count that as intentional, that's to be expected . . .
Or maybe a better question is how grouped should these IDs be between every type of assets? Older games it seems like IDs are very much global due to limitations, but even today I've seen games group monster IDs and item IDs together
I think IEnumerable methods will get boxed though. Even though it's a struct behind it.
Or does the compiler change it?
What example is this just inevitable?
I use generic methods to avoid it getting boxed.
That is one reason why it's important
sorry i misread the entire conversation
i thought someone was asking for help but it was really just a debate about the specifics of the language
if it wasnt managed people would not care, like in C i know whats on the heap since i had to manually allocate it
Yeah, that's why I was confused by that. Knowing this is certainly not a microoptimization.
What happens if you allocate too much in managed and unmanaged languages?
I guess in C you would get segmentation faults?
In managed you can get huge or constant gc spikes
Which slows down the program?
causes hitching
Exactly
cleaning up GC is a total stop the world event, so the frame it happens on will be longer then the rest
its a little better with incremental gc used now, but still not a place you want to be in for a smooth gameplay experience
What's a good place to call GC.Collect?
99.9% of the time never do it your self
if you are having problems with GC, you should be looking into why you are allocating so often
and by problems i mean having the spikes actually negativlity effect your games performance on target hardware
are many ways to avoid it, like the NonAlloc versions of the various physics casts
object pooling any object you are instantiating and destroying often
In C(++) it would just cause more memory used. Segfault is when you try to access uninitialized memory or do some other memory unsafe bullshit.
simpley just reusing in place any large data structures you need
yeah allocating too much and not free is just a memory leak
it wont really error from that till its causeing problems for your whole system
os will kill your program if you try to use too much memory
though you can set the limit
yeah things can get pretty high before that happens though, have had a game that was leaking memory using all my ram and was causing the whole system to slow down due to swapping
Hopefully this is the right section. how would i go about a typewriter text?
Right now I'm doing it with a couroutine just revealing one character at a time
that works just fine . . .
But, this obviously only works if the game is unpaused, and I want to pause the game while talking in dialogue
that's the typical way to do it
Then use unscaled delta time
Also, make sure by "revealing 1 character at a time" you mean using TextMeshPro's maxVisibleCharacters
and you don't mean modifying a string
you can have all the text already there and increase the maxVisibleCharacters field from TMP . . .
yes and thank you it works!
its not incriesing the drinkTimes when i press E, whats wrong?
It's Update, not update
your update method does not run because it's spelled incorrectly. c# is a case-sensitive language . . .
i am incredibly sorry, and ashamed. thank you for your time
when it suposedly deactivates the objects they flicker for some time before really dissapearing, i rlly dont know whats happening pls help
Where are you calling this coroutine from
Nothing locks it from being called more than once, at least not here
Probably starting this coroutine more than once
Debug drinkTimes to see if it's going up more than expected
Or just keep a debug at start of coroutine
Also, if it's not changing, you can do this
public WaitForSeconds waitTime;
This means you don't have to allocate new ones each time
i made it so the counter goes up once it calls the courotine and its fixed, thanks a lot!!
i fixed the issue, I was just creating an empty object and getting the value from it(which was null) i think. Heres the code that works. I dont really understand what 'player' means and i guess thats why i never thought of using it.
{
NewInputSystemValues movement;
public override void EnterState(PlayerStateManager player)
{
movement = player.GetComponent<NewInputSystemValues>();
Debug.Log("Hello From the Idle state :D");
}
public override void UpdateState(PlayerStateManager player)
{
if (movement.MovementAction != Vector2.zero)
{
player.SwitchState(player.WalkState);
}
}```
It has to do with the state machine and base class for example
```public abstract class PlayerBaseState
{
public abstract void EnterState(PlayerStateManager player);```
im not sure what it does so i think i gotta watch the tutorial again
player is a reference to an instance of a PlayerStateManager, which is apparently a component.
Is this garbaj's tutorial?
yea, i dont know how it works, but i dont want to go too far without understanding it, bc im gonna need to use it more i bet
Well, search your code for where the abstract class is implemented then.
Yeah also, if you don't know how abstract and virtual and override works it might be a bit confusing.
Or rather, search where that method is being called from.
the override and abstract makes sense, but i havent really messed with what virtual is
I bet it's called from that PlayerStateManager and it just passes this
yes
Virtual is the same as abstract. Except the base method can implement and is the default method.
Virtual is so that you can override the method.
Yea its alot of new info, but so far i understand it being written, but writing it using my own code is harder to understand, but better if that makes sense
'this' is refering to the game object its attatched to right?
It's always a good idea to write the code yourself if you want to understand it.
No, it refers to "this" instance.
It refers to the instance that the code runs in currently.
seeing it scares me, and also now using parameters in methods is scaring me lol
You only really use "this" if you have name conflicts with a method variable.
that makes sense, i thought of it as the current state its in
Since the code defaults to method variables then class variables.
public class MyClass
{
public int num;
public void Method(int num)
{
_ = this.num;
_ = num;
}
}
The num without the this keyword will refer to the num inside the method.
and this.num will use the public int num?
Yes.
oooooohhhh i just had an epiphery
i had no idea how that related to my code, but after the tunnel vision i see public PlayerBaseState currentState; up top so it is making sense now
Hey, I have an instance of VideoPlayer and after playing a video I need some kind of animation that it disappears, decays within 1 second like a transition of increasing its transparency from no transparent at all to fully transparent. Is there some way to do that?
I would just toggle active state of this game object but that would be immediate, I was wondering if I can make a transition that it fades out within 1 second
What are you rendering the video to?
What's the target?
Camera near plane? It's a 2D camera, should I change that?
Hmm... What about that alpha? Can't you lerp it to 0?
Uh... is that what you meant? This property?
Probably. Check the docs for more details.
Sounds like that's correct
https://docs.unity3d.com/ScriptReference/Video.VideoPlayer-targetCameraAlpha.html
{
currentWeapon = SV.currentWeapon;
Instantiate(currentWeapon);
currentWeapon.transform.position = holderPosFront.transform.position;
currentWeapon.transform.parent = holderPosFront.transform;
}```
this is my start function on my players weapon handler however for some reason it only runs the first two statements
ive put a dubug at the bottom and that still gets called
ive just seen the area Transform resides in a Prefab asset and cannot be set to prevent data corruption
how do i fix that
dont worry i think i got it
You are trying to modify the prefab(the one that sits in your assets), not the instance that you instantiate. Check the Instantiate method documentation. What does it return?
currentWeapon = Instantiate(SV.currentWeapon);
Either way, seems like he got it.
Aight, I need some time to make it work but I think I'm on the good path now, thanks!
void Start()
{
intro.loopPointReached += IntroComplete;
}
async void IntroComplete(VideoPlayer source)
{
float completeTime = Time.time;
float timeDiff = 0;
while(timeDiff <= 1)
{
timeDiff = Time.time - completeTime;
source.targetCameraAlpha = 1 - timeDiff; // here is the alpha change that makes the transition, perfect!
await Awaitable.EndOfFrameAsync(destroyCancellationToken);
}
}
```Yes, this works all perfectly and I got what I wanted, thanks again a lot @teal viper it's not the first time you were so helpful!
I kinda imagine you want NextFrameAsync, not EndOfFrameAsync
I've replaced with NextFrameAsync() but I can't tell the difference, maybe it's a single frame difference that's unnoticeable for me
It seems both are working
it's the difference between waiting until a normal time in the frame, or after everything has completed and when the frame is rendering
NextFrame is similar to yield return null, which is the usual behaviour
Aight
thanks!
Cleaning up some of my prefabs and now I'm debating on how I want to reference all my components. Should I consider just having a root component that serializes all references for each individual component used by the prefab, and then give each of these components a reference to the root (bidirectional referencing). Or, should I just require each component to serialize the references to the components they specifically need?
I'd have to make multiple different classes probably with this root component idea since each implementation would be different depending on the prefab.
imo the scene should not be the source of truth for any gamestate, just a visual representation of it (so you would never need to directly serialize a prefab or its components)
this is all on the prefab itself, such as a player prefab / enemy prefab
even if you do go that route, i think it makes sense to decouple serialization from those components themselves and have something in charge of collecting up/saving whatever things you actually need to persist
for what I've been developing, I've noticed a lot of my components need references to my animator or my stat component, so I thought instead of binding that reference 10 times throughout the prefab, why don't I just give it a reference to a collection of references?
sounds like that's what you'd serialize then?
yeah, I know, but gotta go throughout the whole prefab to match references which can be a lot of mix and matching
I guess it's more of an issue that I do have problems with serialization breaking and me having to go back and rebinding it all
yeah, i don't know of a good solution for that other than my suggestion of 'make it so you don't have to do it'
I had a lot of stuff binding via getcomponent with onvalidate, but the hierarchy isn't always similar to other prefabs so I need to rid of that idea.
is there more documentation on creating state machines for movement? im watching iheartgamedevs tutorials on statemachines and each video it changes the type of state machine he has/rewrites it. Its hard to follow this way bc the earlier videos are flawed so i dont want to follow it, but his recent video is completely different than what i made already
so i dont want to refactor all my code to the first videos machine, then the second, then third, id rather learn the most optimized way from the getgo
You tried Bardent's?
i dont think i have, ill try it
You don't have to start from part 1 on his tutorial, he completely rewrites it starting around 20.
It's also around there he specifically makes finite state machine for managing player movement.
okay, i feel like i dont know enough about them to pick what i need to do now, right now i have 2 movement scripts and a bunch of state machines and im getting stumped more and more as i go
a refactored moving script lol im still completing the new movement script
i have questions like "how do i integrate my scripts into a state machine?" they never show that, just mainly how to build it. or even "How can i make a hierarchical state machine while using the state machine i just made"
no i understand how they work, just not how to implement it into my code and make it work
i get stuck on things like, "should this stay in the movement script or should it be moved to the statemachine?"
Is that really understanding if you don't know both? O.o
no, i understand the concept of them but not how to use them ;D
even then if i try and lookup some written documentation its always about the animator and not the code
the entire time ive tried learning how to make a game i keep getting stumped on WHAT i need to learn. Noone ever tells you the next thing you should do lol
Well for starters, all state machine rely on polymorphism. Basically, it's being able to use something, without knowing what it specifically is.
All the states you've made like WalkingState and IdleState have methods like EnterState and ExitState.
yea im stuck at a point trying to find out how to run Exitstate after a command in EnterState.
basically im jumping twice if im fast enough
Theyre all declared in another script that they should all inherit from, probably called BaseState.
It's just a series of virtual or abstract functions.
you probably want to exit the previous state before entering the next state
and im running into problems where i have to write IsGrounded on every state that needs it or switch the state to Jump on every movement state... its a mess DX
It's a bunch of if statements.
yea thats what im trying to avoid, i know that you can make a hierarchical state machine with jump and grounded able to happen at the same time as the other states without having to hardcode each state to it
I just dont have the bigbrains yet
The tutorial could make a OnGroundState that IdleState and WalkingState inherits from so you don't have to rewrite it over and over. But you might get more confused considering that you're not really used on thinking about these inheritance patterns yet.
debug.logging rb velocity gives 0, 0, 0 even though the player is moving around correctly (this is being called from fixed update)
A hierarchical state machine means that you can have another state machine as a state. Basically nested state machines it does not mean you can be in two states at once. No state should or does that.
stuff like IsGrounded is more of a global flag than a state
oh, god my brain
or rather Uri's suggestion of hierarchical states
ill have to restart and build from what i know until i start getting destructive again, and recreate this in a more organized and structured fashion
Not sure about having multiple state machines.
yeaa, the way uri puts it its not as fun to have
Can't the state themselves be in a hierarchy pattern?
yea like reading left to right, but if i want IsGrounded and Jump to be able to happen from any of them, thats alot of spegetti the whole thing was implemented to avoid
BaseState: Defines basic functions for each state.
- OnAirState
- OnGroundState: Defines the functionality to jump or transitioning to OnAirState when not in ground.
- WalkingState: Walking left or right.
- IdleState: Standing idle.
this hurts my brain, i must absorb
Real.
You dont need a onGroundState for a statemachine like that
it doesnt help the same guy put out 4 tutorials on the same topic within a 6 month period of revisions
Well dont follow that tutorial then
It just exists so it's reused for WalkingState and IdleState.
Yep, state machines tend to be about creating hard boundaries but games tend to mostly be full of soft boundaries. It might not be a good fit for the movement in your game and I'd recommend just starting with clean procedural code to get a feel for what your actual needs are
eya im watchin this 2d one now lilac mentioned
@night mural i refactored my code to look really nice, but then got to a spegetti-if halt from the multiple features i wanted the movement to have. I want basic crouch, run, jump, walk, and idle movements, which is simple, but i know i will need more than that for future games
sometimes complex things require complex code
just be careful getting stuck re-implementing the same thing a bunch of different ways before you're sure if you actually need it and why
okay ill remember
just stick stuff in methods even if it's not reusable and it'll look less spaghetti
Guard clause exists.
nah, if things are truly coupled together, keep them together.
if (!grounded)
{
state_machine.ChangeState(onair_state);
return;
}
if (input.x != 0)
{
state_machine.ChangeState(walking_state);
return;
}
This much is unavoidable.
^^thats how i have it rn, but the jump state jumps twice if im quick enouch
im okay with that
There might be an issue on how the state is changing or what state comes after jumping.
i wanted to implement a counter for it, but failed lol. so unless i want to jump high randomly im stuck here
that leads to why i figured changing the state from both idle and walking to jumping seems redundant and could cause that
it goes to walking, i heard something about substates for when it could go to either of them, but idk how it works
When you jump, it goes into OnAirState right?
i dont have onairstate, but rather Jump state. but yes, when the spacebar is pressed, the Walking/Idle state checks if its grounded then changes state to the Jump state. The EnterState() function runs playerMovement.Jump()
Does your jump state have a ground check?
and the update function checks if its grounded to change it to walkstate.
it did, i took it off since i figured its asking twice bc its switching states
i had it on the method, state, and previous state at the same time too
Then I might be able to guess why.
You're not instantly in the air when you jump.
So
on ground -> jumping state -> on ground.
It's probably because you're not high up in the air enough that it instantly goes back to ground state.
You can fix this by having a minimum time to be in jump state.
yea im seeing it now, its called 6 times every 1 button press
Sounds cracked.
im guessing a corutine would work?
The states should suffice with only on frame updates.
couldnt i put a set amount of time before it switches? idk how to add a certain amount of time to it
Exactly.
You have the EnterState method.
Add a float parameter and set it to the current time.
And another float parameter on how long you have to stay on jumping state.
Add those two floats on update and check if it's less than current time.
Another way is to make the grounded/jumping condition more robust. For example, checking the character velocity. If it's upwards, it doesn't make sense to transition to grounded state.
what if hes walkin up a hill? wouldnt that go up in velocity?
I don't like this method when you have to add stuff like vertical platforms tho.
Well, it depends on the project of course, but the point is, to identify correct conditions for transition. If you're going back and forth between states every frame, it's not a solid state machine.
is there any other way to have a good state machine with jumping? i cant think of anything else that could check more accurately than isgrounded
You totally need a isgrounded.
If you only make the check when you are already in the jumping state, that would prevent it from transitioning back into grounded. And you shouldn't transition from grounded to jumping just with that one condition.
So slopes shouldn't be a problem.
What about jumping on a vertical slope?
Jumping and landing.
Also, I wouldn't treat vertical platforms the same way as a normal grounded state.
What about it? The gravity direction is still the same.
You can't land on something while moving upwards.
Unless you have custom physics and orientation mechanics.
Like changing the gravity to point up and stuff.
Jumping and landing while trying to climb up the slope at the same time.
You probably can't transition back to ground state if you're using Rigidbodies.
Okay, I see that one case. But that can be handled separately.
i figured i could do something like jump in the enter state if a bool is true, then set it false, then go to the ExitState() and set a bool to true and switch
it seems easier if i just want to jump once
Your jump force isn't on enter state?
nah, its in the movement script
That's fine too.
For example instead of simple velocity direction check,check it against the surface normal, and if the directions meet, consider it grounded.
But you still have to prevent false positives when the jump state changes to the ground state.
i find its sufficient to just check the grounds normal along with if you jumped recently, you are likely gonna have a jump cooldown anyways. So you can use this cooldown to see if it makes sense for the player to be grounded
yess just noticed. dangit
Yes but you don't change how your ground check works.
Do as dlich and I suggest to only add the extra conditions specifically on the jump state.
so i took out the ground checks for the other states, is it good enough to just have the groundcheck on the updatestate for Jumping?
nah its still happening
Why did you took out the ground check for other states?
oh wait what are the extra conditions
Only the jump state prematurely moving to ground state is the problem.
how do i get it out of the jumpstate then?
Use the isgrounded AND minimum jump state time or a y velocity check.
uhh 1.0 is equal to 1 minute right?
hey would anyone like to give a brief explanation of instantiate? (ive only ever used it for guns & shooting so my brain just automatically goes: hehe funny gun word).
Time is measured in seconds in unity.
You only need like a fraction of a second for a minimum time.
1 is too much, .001 doesnt work, .01 doesnt exit still
To put it simply it creates a copy of the object.
For more details I recommend checking the documentation.
0.1f
ok
that was my basic idea
like a cloning feature
nvmd didnt work
ohh wait yeah
that makes sense
i was instantiating the bullet and adding force
im learnding
using Unity.VisualScripting;
using UnityEngine;
public class PlayerJumpState : PlayerBaseState
{
PlayerMovement playerMovement;
float currentTime;
float waitTime = .1f;
public override void EnterState(PlayerStateManager player)
{
currentTime = Time.deltaTime;
Debug.Log(currentTime);
Debug.Log("JumpState Enter");
playerMovement = player.GetComponent<PlayerMovement>();
playerMovement.Jump();
}
public override void UpdateState(PlayerStateManager player)
{
if (playerMovement.IsGrounded() && currentTime > waitTime )
{
player.SwitchState(player.WalkState);
}
}
}```
why do you have a specidic float for deltatime
no idea
Why is current time using delta time?
no idea
Time.time for current time.
what is currenttime meant for
oh ok
@vale karma
loll yea i never used Time.time, so i looked at whatever options come after the .
Also your if check is also wrong.
Time.time > currentTime + waitTime
Rename current time to
The time the state became jump state.
Crunch that sentence lol.
stateStartTime might work.
@vale karma
okay i got it all written, lets see if it works
PlayerMovement playerMovement;
float waitTime = .2f;
float stateStartTime;
public override void EnterState(PlayerStateManager player)
{
stateStartTime = Time.time;
Debug.Log(stateStartTime);
Debug.Log("JumpState Enter");
playerMovement = player.GetComponent<PlayerMovement>();
playerMovement.Jump();
}
public override void UpdateState(PlayerStateManager player)
{
if (playerMovement.IsGrounded() && Time.time > waitTime + stateStartTime )
{
player.SwitchState(player.WalkState);``` this works
What script is this?
jumpstate
Ah ok.
unresolved question, still havent figured it out.
are you applying force or changing transform
debug.log to see if targespeed changes
force isnt added instantly, it is added after the physics simulation step. your debug.log wont be accurate
would lateUpdate be better?
no, as that depends on framerate and will still have the same issue. Is your debug always giving 0?
can u show the inspector for the rigidbody? also maybe other code is affecting the rigidbody in some way
i got it running, jumping, and sprinting correctly 😄 ill do crouching tomorow
maybe look at the physics debugger to see its velocity instead. i dont see why this would always log 0, unless the log is only happening when the velocity is 0 beforehand.
thnks guys catch u tomorow
theres likely other code thats affecting this, or the code isnt affecting the object you think it is
physics debugger agrees with debug.log
that it is 0? then you are likely not affecting the object that you think
if you said the object is moving properly, or you have other code moving it
this is the only other place the rigid body is being referenced and the velocity is correctly updated
here where it is suspiciously not updating velocity correctly, if i comment out the addforce line my character cannot move so it is doing something
why u have AddForce of velocity change and inpulse?
So far jumps worked fine with impulse
the impulse is being used for the jumping and velocity change for walking
its definitely working since my guy is walking around just fine
values just arent being updated though
as the impulse works correctly i am applying the force to the right object, might i be using velocitychange wrong?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
am i able to implement MoveTowards ther?
i want the object that gets the knockback to move to that position so it looks cleaner
you have Vector3 with just 2 variables
yea
there really isnt much to do wrong with it, its just an enum. I dont really know whats wrong with it, i think there is still other code affecting this. Put the same code that you've shown on a cube in a new scene, it should work just fine and debug the values properly. If it doesnt, then it is a bug and you should report it then
move toward:
T start,T end, float amount
T something_normalized=(start-end).normalized
if(start+something_normalized*amount>end){
return end;
}else{
return start+something_normalized*amount;
}
```you need clamp and normalization
I would belive more that he has issues with code then bug with rb that is used a lot
am i able to implement MoveTowards?
yeah moveTowards will move it to position
but how do i implement that?
dont reinvent the wheel btw
I love reinventing a wheel
I spent 2 days coding FPS controller only to decide im done and understand how Unity Asset one works
can u help me with the MoveTowards?
im to dumb to do it
no wait
I'm not sure if it's actually what you wanted, but here's Unity's impl
// Moves a point /current/ towards /target/.
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta)
{
// avoid vector ops because current scripting backends are terrible at inlining
float toVector_x = target.x - current.x;
float toVector_y = target.y - current.y;
float sqDist = toVector_x * toVector_x + toVector_y * toVector_y;
if (sqDist == 0 || (maxDistanceDelta >= 0 && sqDist <= maxDistanceDelta * maxDistanceDelta))
return target;
float dist = (float)Math.Sqrt(sqDist);
return new Vector2(current.x + toVector_x / dist * maxDistanceDelta,
current.y + toVector_y / dist * maxDistanceDelta);
}
there's not much you can do to make it better than it already is other than replacing those divisions, but that will introduce other issues and new edge cases.
it should be fine. what part are you stuck on
is it possible to connect a server with other people who have the build for free
good morning. what goes in underlined pharantesis? is it just int value or something custom
if i wrote int 0 would it start from zero
if you call the function with AddLives(0)
then the value will be 0
so 1st line from the function
will be
lives += 0
i gotta make it lives=lives+1 yes?
oh
wait
right
lives is 10 this way
for initializing it i may use a timer too later
someone writes code on paper omg
also if you want to change same variable you can do this
+=,-=,/=,*=
its basically a = a+-/* number
yeah.
i read it easier this way
thats why
writing code on paper is elite
of course, you just connect to the server, whatever the server may be.
before IDEs we had paper boy👴
hey could anyone help me : (
does the underscore prefix of a var and private do the same thing ?
i tried making an update score function in a box collision script but it doesnt update the text on screen
so maybe show the code?
lmao good point
wdym by this?
the name has 0 affect
Prefixing a variable name with an understore does absolutely nothing. It's common to do with private variables to indicate they are private
yeah thats just naming
This is about as effective as writing code on a phone
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LogicManager : MonoBehaviour
{
public int playerScore;
public Text scoretext;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore += scoreToAdd;
scoretext.text = playerScore.ToString();
}
}
using System.Collections.Generic;
using UnityEngine;
public class PipeMiddleScript : MonoBehaviour
{
// Start is called before the first frame update
public LogicManager LogicManager;
void Start()
{
LogicManager = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicManager>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
LogicManager.addScore(1);
Debug.Log("added score");
}
}
}
the first one is for the text to show
the second one is the box clission
Consider actually debugging your application. Add Debug.Log statements to addScore for example.
i did : (
See if it's called at all, and see if addScore actually logs the value you expect to write to the screen
Ok so what are the results?
seems that OnTrigger isnt beinbg triggered : (
Ok so why are yo not telling this? 🤔
do you have collider set to trigger?
It's very important you share as much info as possible
ok so an underscore has 0 effect? Cuz ive been trying to look up on google and I keep getting that if you don't have an underscore you might have to do something with classes and pointers (this-> )
Say I have a script on an object that inherits from another class that extends MonoBehaviour,
ParentClass : MonoBehaviour
SubClass : ParentClass```
and I have that subclass attached to an object. If I ask for the parent class in code ```cs
FindObjectOfType<ParentClass>();``` will it pick up an object if the subclass script is attached to an object?
private would be to make it inaccessible where as the underscore is purely for readability sakes basically, right ?
@torn gyro Please follow the steps indicated here and see if this fixes your issue https://unity.huh.how/physics-messages
mhmmm
And consider also logging your trigger behaviour considering that's the part that fails according to you. Place Debug messages and see if they're actually not called. Currently your code only checks if the trigger activates on a certain layer.
https://unity.huh.how/debugging And read this
my game object is set to layer 3
Yes, but is the trigger called at all?
2 d
The worst part about helping somebody with debugging their application is when somebody else ends up spoonfeeding the answer
Thanks @earnest atlas
oh theres one more issue that is easily traceable too
OnTriggerEnter2D (collider2D other) is for 2D
OnTriggerEnter(collider other) is for 3d
the context menue doesnt show under Logic manager
does that have anything to do with it
I have no idea what is ContextMenu
OH SHIUT
i fucking didnt read that shit
When debugging something like this you might be better off following the most basic example first
So see if copy pasing the method from the wiki does anything
Not increase score, you need to write there addScore
public class ContextTesting : MonoBehaviour
{
/// Add a context menu named "Do Something" in the inspector
/// of the attached script.
[ContextMenu("Do Something")]
void DoSomething()
{
Debug.Log("Perform operation");
}
}```
That's not at all how to fix the issue, please stop helping if you have no idea how it works 🤦♂️
You have already spoonfed the previous answer instead of providing a good way to debug the issue, maybe wrap it up for now
@torn gyro See if the method from the wiki works for you.
👆
You can't add it to a method that takes arguments
OMG why you guys bully @earnest atlas
are they?
his solution was correct
Im kinda not looking
idk :/
this fixed it
but he wasn't bullied for that lol
yeah I had experience with exactly same issue u had
lmaooo thats a bully statment
that's a fact
im not even sure who he adressed that
to u i think : P
The problem is that I'm trying to get you to debug your issue so you can fix any future issues yourself, and they proceed to spoonfeed the answer instead.
Now you have no idea how to fix any future problems
who?
chat gbt : P
The answer was nonsense so, I can see why they said that
I understand people love to help, but please don't spoonfeed an answer
And please don't use ChatGPT as a beginner...
they have been told this several times
im second year cs 
I see. I don't check this channel as often as I used to
spoonfeeding should be against the rules lmao
my code for this is
if (transform.position.z>35 || transform.position.x >35)
{
Destroy(gameObject);
}
else if transform.position.z<-35 || transform.position.x <-35)
{
gameManager.Addlives(-1);
Destroy(gameObject)
}
how can I make it so that players lives decrease each time a gameobject gets destroyed in either x or z axis? for example my code includes || thats if position is ... or position is... I dont wanna use the code in the screenshot as I want it to be as short as possible
so, a beginner
gimme internship pls :/
there is "||" in code but discord marked it as spoiler
It's a guideline in #854851968446365696 but more specific
in if pharantesis
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
that ^
a lot of spoonfed questions would be reduced by only answering if they actually debugged their code / printed to console
Yes, that's kind of what I was hinting at
you
@earnest atlas @rare basin @burnt vapor thanks yall < 3 this issue took me 2 hours btw i had to look at every single aspect of the project until i gave up and came here
you?
The majority of questions in here could be fixed by learning to debug
posting a whole block of code without a single print statement and asking why dis dont work is where my help stops ;)
Also knowing that it exists. :0
Please read about debugging, in case you have not done so yet. https://unity.huh.how/debugging
ok
you know i had to restart like 5 times cuz i keep pressing play button without saving :/
What do you mean restart? Code should not disappear if you forget to save
What's the problem with this code?
Coffee script?
Just what the site assumes to be the language used, it's often wrong
Probably cause of the first line.
Or the fact they wrote the entire question alongside the code 🤔
Definitely that.
Side note, if we suddenly talk about the odd things they did while asking for help, I'd get a bit nervous.
can I update directly a specific axis of the size of Sprite Renderer ?
or is it like Transform and you have to give a whole Vector
You can't.
It's because it's a getter/setter. Not an actual field so you can't change something inside directly.
theres no problem. unity wrote this code this way but i wrote it differently and i dont wanna change it because i wanna make it as short as possible. in unitys version players lives decrease when animal is destroyed in x and it decreases when its destroyed in z too. in my version it decreases by one if it gets destroyed in either z or x
i wanna make it so that if it gets destroyed in x or z players live decreases by 1 instead of if it gets destroyed in either z or x
So what's the question?
If there is no problem, what's the meaning behind your message?
it is how can i make players live decrease if animal gets desroyed in both z and x (-2 lives) instead of it getting destroyed either in z or x axis (-1 live)
i used "||"
unity didnt
Wdym by "unity didn't"? Unity is not a living person. It doesn't write code.
... Use &&? Your question is confusing
ill show you
Okay, so did that fix the issue?
I assume you want to use && rather than ||
desroyed in both z and x
then yea use &&
if you want both conditions
why did you use || then
ok ilk try
i dont know ill try when i get home
I still don't get what "unity version" is?
So you didn't even try that code?
ok, so what?
Wtf is "unity version"??
from !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Unity is a game engine it doesn't write code!!
they are following a tutorial
yeah
from unity learn
Ok, so it's "code from a tutorial". Not unity version.
ok so what about it
here
that's unreadable
i think using && will fix it
my text look ugly :/
He wanted to check both cases instead of either one, I guess. Hence why && should be used rather than ||
What are you talking about? 🤔
i will
I’m new to Unity so Hopefully this is an easy fix. So everything looks super low res for me. I wish my images looked high res. Even SVG looks low res even though they’re vector nodes, I don’t get that at all but I assume Unity doesn’t play with svg yet? the black outline graphics is SVG, the rest are PNG with alpha. Take a peek at my three di...
Or just google "Unity low resolution"
also this is code related channel
thanks
anyone know what "unity NullReferenceExeption: Object reference not set to an instance object" means
you probably made some code, or copied some code, but didn't actually tell it what the fields mean
imagine i said "there's a person in this room called larry" but never told you who. you can't bring larry back to me
the computer doesn't know what the objects its trying to move are. you have to tell it
oh ok thank you
Hi everyone, how can I solve this problem?
ok i dont understand this in the slightest
basically im trying to implement a burst system for my game
so being able to fire in bursts
That looks like an internal error. Do you have any custom shaders or anything related to shaders being changed?
firing multiple times with one shot i got sorted out, but i cannot get delays between shots working
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Look up coroutines, and when you shoot use a coroutine to apply delays between shots
already did that but it doesnt seem to work
show the code then
Yes it does. What have you tried?
no, I just updated unity, so I use the new HDRP version 14.0.10
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what is AE/Leaves
that looks like a custom asset
Sorry, not experienced with HDRP. Try restarting Unity or downgrading if the issue persists
for enviroment
Or ask in a channel with people with experience
grass
{
if(deathOnce == false)
{
deathOnce = true;
isDissolving = true;
EH.StartCoroutine(EH.Dissolve(gameObject));
EH.enemyCount -= 1;
int randomNum = Random.Range(0, 4);
for (int i = 0; i < randomNum; i++)
{
GameObject spawnedCoin;
spawnedCoin = Instantiate(Coin, gameObject.transform.position + Coin.transform.position, quaternion.identity);
spawnedCoin.GetComponent<Rigidbody2D>().AddRelativeForce(Random.onUnitSphere * 1500);
}
}
}```
my coroutine isnt activating
then that asset is causing issues
grass shader
it might not be made for HDRP
What do I need to look at. Line 79?
That's not how a Coroutine works
A Coroutine does not magically halt code in a non-coroutine just because you start one
oh
And you can call a coroutine and yield that one to add a delay, or just add a delay there directly
is there a way to solve it?
Code in Unity is synchronous. Coroutines fake asynchronous code running in the background by having Unity invoke these yield commands. Kind of a complex topic.
You can also make actual asynchronous code with Tasks. If you make that function a Task it can also use delays
But in Unity async code works the exact same as Coroutines
But still very good knowledge to have
Starting with Unity 2023 they have a better system for this https://docs.unity3d.com/2023.2/Documentation/Manual/AwaitSupport.html
Have fun reading
im using unity 2022.3.13 sadly
Regular async still applies, or continue using Coroutines
Async is just better because the flow is a lot more clear and undisturbed
And external libraries will use it, if you ever need them
Or upgrade 😎
how can i get a hollow circle? is that possible without using some renderer? i would also like to have it as a prefab with other shapes inside it
You mean a circle mesh with a hollow inside? Consider asking a channel related to that
Probuilder for example, is a tool that allows you to easily make geometry. Idk if it can make a hollow circle as easy
thanks ill check it out
I'm using URP and new input system, and I just noticed randomly that if I press both sticks on a controller in play mode a debug stats window pops up. Kinda cool, but also.. where's that coming from? I'm pretty sure I don't have anything to trigger it in my input actions, and my canvas event system is setup to process the new input system. It's called DebugUIHandlerContainer so the debug means this will NOT be in my release build, right?
Not a code question, try asking in #🖱️┃input-system or #archived-urp
also.. just do a build and test it ?
hello everyone.
[System.Serializable]
public class CapturedPets
{
public GameObject thePrefab;
public BaseClass Stats;
public Level Level;
public EnemyType Type;
public EnemyRarity Rarity;
}
how can I actually save the reference to a gameObject? Let's say I plan to use json.
What this class will later do is at the turn-based battle start it will instantiate thePrefab gameobject and then load all the data below.
Is making a string with the path to the gameObject instead of direct reference a way to go?
you don't save that specific reference per say, instead you construct a new object of that type and populate it with the data you written to your json
you can cut down on the data you need to write and read if that specific data is non-unique, such as defaults, which then you can just serialize an ID to be used with a lookup table that you construct from all your prefabs/SOs on startup
I have lot's of 3d models... so I am pretty sure you are right, but that won't be possible for my case sadly.
Meanwhile I found some solution here and that would be making a dictionary of gameobjects and their names as string... I think that's what I was looking for
basically Instantiate(Resource.Load(“object path”))
so the code would be changed to something like that:
[System.Serializable]
public class CapturedPets
{
public string PrefabName;
public BaseClass Stats;
public Level Level;
public EnemyType Type;
public EnemyRarity Rarity;
}
I think it's solved. Thank you.
Names are fine too if you wanna do it that way, but always a chance that you've create a prefab of a similar name which is why I suggest adding some IDs in one of your components and do lookup by that.
Ah, if it's all in the same directory it probably would resolve itself
hmm... could also be int and that would indicate the exact name of my 3d models... they all have different int names like this:
nah, not an int per se, still string, but anyways...
guys, i need some help, i can't move in my scene, if i press w it does not go forward
umm... which movement controller are you using?
in scene
i can only move the view with the mouse
oh... use arrows? )
thats the pixel count
are there any gameobjects in the scene so you actually are liek dead sure it's not working? ) because I guess it might be tricky in an empty scene
ye, there are some game objects, i just moved far and it's blocked now
reopen the project
ohh
no
the furhter you are from your game it moves slower i think
happens to me from time to time
doubleclick on the object to get close to it I think?
oh, but i already tried to re-open my position is still the same
yeah
works? )
😄
omg
ye...
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.

great )
after the insantiate it doesnt move
more details?
could you send the wohole code
yea
isn't speed set to 0 there? 🙂
Coin.transform.position = Vector3.MoveTowards(transform.position, Player.transform.position,0);
``` pretty sure this 0 is speed
it should be float actually 😄
my bad
or idk... look at this:
transform.position = Vector3.MoveTowards(transform.position, target, 15f * Time.deltaTime)
that's a part of the string I use to move some of my units around...
and animSpeed is a float
yea
also I guess * Time.deltaTime is quite essential there
still nothing is happening
okay
if it's not working, sorry, can't help any further, no idea then
You're not really moving it. Only once after it's instantiated.
0.5 sec after
And incorrectly at that as well. TylerWin pointed that.
Hi. I have a question about optimizing the script: I have texts that show the float value. They work in void Update every time, but if I add: "(if objectsLights[i].activeSelf)", will there be any difference in performance? If the 25th line is removed from the screenshot, will the performance be the same or will it differ? if I added that the text does not always change and does not load the system (according to my logic)
private Vector3 startposition;
private float animSpeed = 15f;
while (MoveToPosition(startposition))
{
yield return null;
}
private bool MoveToPosition(Vector3 target)
{
return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
}
Idk, that's what I use. Also in terms of IENumerator
it doesn't make a difference in performance
unless you have 10000000 objectsLights
ye thats what i want
Thanks
i want it to move to the player after its instantiated
It probably would be different but not by a lot. Probably you wouldn't event notice the difference unless you scale the loop to some million iterations.
my jump action is able to jump when im near the ground, i think the raycast is returning true too late
Well, it doesn't. It moves once. Changes position once. One time. It doesn't keep on moving towards whatever you want it to move.
oh okay
you need to put the MoveTowards in Update
If you really want to optimize it, make it so that the text changes only when the value changes
{
int hits = Physics.OverlapSphereNonAlloc(transform.position, capCollider.radius, groundedResults, groundedLayers);
return hits > 0;
}``` can this be written better? or am i missing something with this IsGround check?
Maybe make a velocity check as I suggested yesterday.
*in addition to the grounded check
thats a good idea
how do i make the object to move till the player is reached?
Move it every frame.
is there a way to make isgrounded shoot down less than it is?
how
at which point is void Start() exectuted after instantiating the object with the script that contains Start on it?
However you like. There are many ways.
for example a for loop?
mostly with update, unless your using rigidbodies
ye i know
The values will change when the light object is turned on, that is, if you still need to leave?
Does loop make it execute every frame?🤨
I suggest going through the beginner pathways on unity learn.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
then change the values only when its turned no
on
not constantly in Update()
please try to implement this code: private Vector3 startposition;
private float animSpeed = 15f;
while (MoveToPosition(startposition))
{
yield return null;
}
private bool MoveToPosition(Vector3 target)
{
return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
}
via events preferrably
okay
that won't work
due to floating point precision
do you mean to make the place where the isgrounded is detected more down?
thanks
Ok. Thanks
well it works for me?
doesnt mean its correct
Well that sounds like a good spot to set the text then. No point in setting the texts every frame if they don't change every frame
you could look into navmesh as well, its a part of enemy navigation it may help u
I mean what else would suggest it's incorrect?
as i said, floating points
Vector3 comparison makes an approximate comparison. Though, I agree that it might not work under certain conditions(not due to floating point error)
the coroutine stops and waits for object to reach it's destination then goes on
what's the problem?
no more up, its returning true even when the player is in the air
its too leanient with the raycast rn
what is worth looking into is creating a empty game object and naming that Ground Check, make a script to check for isGrounded where the empty game object is, thats how i do it in my game, easily changeable and scaleable for the future
I also got an alternative from some source 🙂
IEnumerator DropCoin()
{
Vector3 position = transform.position;
GameObject Coin = Instantiate(essenz1, position, Quaternion.identity);
Coin.SetActive(true);
yield return new WaitForSeconds(0.5f);
// Define the speed at which the Coin moves towards the Player
float speed = 5f;
// Calculate the direction from the Coin's current position to the Player's position
Vector3 direction = (Player.transform.position - Coin.transform.position).normalized;
// Move the Coin towards the Player
while (Vector3.Distance(Coin.transform.position, Player.transform.position) > 0.1f)
{
Coin.transform.position += direction * speed * Time.deltaTime;
yield return null;
}
coin.essenz++;
}
if what works for me won't work for you. Maybee this will. Sorry, haven't tested this one
from chatgpt?
i feel like thats exactly what i got goin on already, but in the same script just using a method
i got an empty player object at the feet
Preferably, give answers that promote learning, instead of spoon feeding.
try moving it up
real
thanks i try it
as i said it lol, im gonna multiply by 1.5? i think thats gonna work
well... I am learning myself and at some points I would be daaaamn grateful to get a ready solution and not just well, try this (abrakadabra for me) and then get back. But will note that, sorry if that's the problem
that's not a good way to learn things
to get ready solutions for issues
yea that was it, the empty was at the ground already,so i just multiplied it by 1.5 and it worked
I learn things in different ways )
They would just be back with a similar problem soon. You should lead them to discover the correct solution themselves and gains some understanding in the process.
okay, but don't force your way for the others then
I don't... daaayuuum... just wanted to help. And maybe learn myself something in the process
and hope you did, to don't spoon feed people ;p
😄 ahahah 😄 for damn sure
sometimes some stupid problem holds back from doing big things. So IMO I would prefer the person to get stuck learning what's wrong with their huge gameManager instead of being stuck at coin not moving 🙂 Not arguing, just clarifying my standpoint )
Game development(or any development really) is all about this small things. You can't use a walkaround for everything. And I really doubt you can implement something "big" when you can't even solve small issues.
true. But that's a bloody noob speaks in me I guess
if you have huge gameManager, then something went wrong with your code architecture
small sidenote 😄
bro doesnt work anyway
Single-responsibility rule
wow... that's strange. Then it's up to pros to help here )
ahaha 😄 Well... yeah... I just could not think of something epic enough 😄
i once was revieving an intern and his job recruitment task, and he did entire game logic in a single script Game.cs with almost 4k lines
Instead of copy pasting code, try to understand what your have and why it doesn't work.
i do
It's fine to ask about how things work and why they don't. Do make proper learning too though.
yea
I have a odd problem trying to get Cinemachine to work, ive used it in the past without problems but i cant seem to get it to work normally at the moment.
i set up a very basic player movement for a 2D game, WASD movement using just GetaxisRaw.
Cinemachine set up 'correctly' with MainCam having the CineBrain and Transform of Player in the Virtual Camera.
If i move around with WASD the Camera will do nothing, but if i drag the character around in the Editor the Camera Follows that... why wont it follow the Character when i move it in game..?
Provide more details on your setup.
Not sure what else to include its incredibly bare bones

