#archived-code-general
1 messages ยท Page 82 of 1
yes, and if you were to somehow destroy the object while still holding a reference to it, this would crash your game
But unity has memory allocated for this object, I can even return it back to scene with all previous state it has.
you have memory allocated for it
the C# runtime will not get rid of the object until all references to it are gone
all you have to do is myReferenceToTheObject = null;
and it goes away
or remove it from whatever list or collection it's in
Don't really understand what you mean by "me", "unity" and "my code".
Memory with object data is still present, that is what I'm asking about.
again: what is the problem you are trying to solve here?
what is wrong that needs to be made right?
Discard whatever reference you have to the object when you destroy it
it's up to you to manage those references
Unity cannot do it for you
What would you expect to happen if you did this?
Destroy(x);```
Then later on `x.DoSomething();`
What should Unity do for you in that scenario?
Ignore it?
Throw an error?
Something else?
I have the memory allocated for destroyed objects and wanted to find a solution to clear it without checking all places with references to it.
This would leave you with dangling references to invalid memory.
NullReferenceExpeption
This is illegal.
It's not a state that the C# runtime ever wants to be in
It's not a null reference though
what if that memory gets re-allocated by somoene else?
now you're stomping all over some random object's data
Also where possible it's a MissingReferenceException in Unity
Hmm, I think I get it.
this is completely forbidden, by design
if you want the object to go away, get rid of all references to the object
Thanks for the explanation.
you could absolutely do this in C++ or some other unmanaged language
but then you'd be left with dangling pointers
Hmm
Can't it just check all references to this object and rewrite this reference to null?
it could but that would be a waste of time and resources
very slow
it would also be very surprising
it would have to search the entire memory of the application to find those references
a reference-counting GC might not know exactly where the references are
or maintain some data structure indexing all references which would itself take a lot of memory and be slow to maintain
i forget how C#'s works
ah, no, it traverses all objects in memory, starting from a set of roots, and collects anything that's unreachable
so that's not reference-counted
at least, that's how it works by default. Unity could have its own special flavor.
regardless, it would be very, very annoying if your valid references could just...disappear
Regardless Destroy is not even part of C#
and certainly wouldn't be hooking into low level C# things
when a UnityEngine.Object is destroyed, it doesn't actually "become" null; it just starts returning true when compared to null
i was a little surprised by that behavior when I started out, for sure
Hmm, I understood
Thanks for the answers
How can I completely delete object from memory even if there are references to it?
you wait until the runtime defragments allocated memory, creating enough contiguous free space that it decides to reduce the amount of memory reserved from the OS. on video game consoles, the games usually have exclusive access to almost all the memory, so in principle there is nothing to do
it is a misconception that there is One Right Way to Do Memory. it's certainly not how it is done in C++, which by the way, lets you do whatever you want
at least it has smart pointers now
yeah i think the misconception comes from why game developers should care*
the performance sensitive part of all this is where the memory is located. if it is on the heap, Big Video Game Developer is already mad
it doesn't matter if the heap is RAII, ARC or GC managed
C++ solves this by letting you accidentally free a stack pointer, thus letting you create the unholy Steap
actually, I haven't tried that in C++; I've only done that in C
So, is there a way to somehow check all references to destroyed object to know where I forgot to clear my reference?
Python has facilities for that. I don't think C# has a convenient way to do it.
to come back to the point from yesterday, here i have some video and script refs idk if anyone knows why unity just enters pause mode
well you don't really need to do that
if you Destroy a gameobject that is in the slot of public GameObject someInspectorSlot, it will indeed be destroyed
but i am not sure what your goal is.
one thing this should illuminate for you is that destroying game objects doesn't really matter much a memory point of view, but creating few of them in the first place does
In a practical sense, if you have short lived objects how many references to it could you possibly have?
it should be fairly obvious
it is confusing, but Unity.Object like GameObject is a kind of smart pointer, so the only thing that is stored in the inspector slot is a pointer to the game object. once you call Destroy on it, by the start of the next frame, the components on it will not have their Update loops called, the primitives in the fields on those components will be available to be reclaimed by the GC, and the Unity.Object referenced will be eligible to be reclaimed if (recursively by these rules).
a video game is not a server, so for the most part, memory is never returned to the system. however, the unity runtime itself of course knows when you no longer use some memory, and makes it available to be used by something else
a component is a unity.object. when you destroy a game object, destroy is called on all its components. if you merely have no references to a component or game object, and never destroy it, it's going to vibin and survivn
one way to think of this is that the scene has a reference to all the stuff inside of it
hi,
is it possible to call the begainDrag and Dragging events without actually do the dragging ??
yes but it is very rare to do that
you can use ExecuteEvents to call any handler, however the state of the pointer event data will be wrong
could you give me an example ? , I dont know what you are talking about.
and how to make things right ?
there's also OnInitializePotentialDrag if you want to intercept the logic event system uses to decide whether something is a click or drag
actually is json manifests count as code?
i think thats the stupidest think ima ask today
you did kill some of my brain cells yes
happy monday
all im trying to do is have a manifest.json line point to a folder ABOVE the packages folder which is a local path
just how my builds are structured
i have this local list and when i try to add a object it tells me that the local variable "attacks" has not been defined
you mean it hasn't been initialized or assigned
which it hasn't
re-read the error
then its not been assigned
correct
you didn't assign it
= is the assignment operator - so you'd need to have used that somewhere to assign it
e.g. List<AttackInfo> attacks = new List<AttackInfo>();
thank you
Seems weird to be creating this list right here and adding to it though... My guess is there's some existing variable you probably meant to be working with or something.
Hard to say without seeing more context
anyone know how to close the TouchScreenKeyboard in unity? For some reason, mine never closes. It opens up correctly the first time, but when I click Done on the keyboard, it closes and opens immediately again
.
hi
i want to store textures of 9 .fbx files in ONE folder, but it keeps extracting the textures for every fbx.
and they share similar textures.
perhaps you have a bug in your code causing it to open again
You can choose whether it imports materials/textuers etc for the FPX in the import settings. This has nothing to do with code though so you're in the wrong channel
---Script A---
public class P_Controller : MonoBehaviour
{
public bool RotChanged;
private void Update()
{
}
void OnRotation(InputValue value)
{
RotChanged = value.isPressed;
}
}
----Script B----
P_Controller controller;
private void Awake()
{
controller = GetComponent<P_Controller>();
}
void Update()
{
Rotating();
ChangingRot();
}
void ChangingRot()
{
if (controller.RotChanged)
changeDirection = true;
}
void Rotating()
{
if (changeDirection)
transform.Rotate(0, 0, RotSpeed * Time.deltaTime);
else
transform.Rotate(0, 0, -RotSpeed * Time.deltaTime);
}```
Hi sorry, But why doesnt my new input here register?
I press D but nothing is happening ๐ฆ
I'm not seeing any input everywhere, I don't see RotSpeed being assigned, I don't know what OnRotation is, or what InputValue is
oh haha. its a new input system. Sorry the rotspeed is just my float value. i didnt put up my code in full.
[SerializeField] float RotSpeed;
[SerializeField] bool changeDirection = false;
P_Controller controller;`
private void Awake()
{
controller = GetComponent<P_Controller>();
}
void Update()
{
Rotating();
ChangingRot();
}
void ChangingRot()
{
if (controller.RotChanged)
changeDirection = true;
}
void Rotating()
{
if (changeDirection)
transform.Rotate(0, 0, RotSpeed * Time.deltaTime);
else
transform.Rotate(0, 0, -RotSpeed * Time.deltaTime);
}
I'm still not seeing where any sort of input in here
So my only guess is you're not even checking if you're pressing it
What is P_Controller?
I would hazard a guess that OnRotation is supposed to be getting called by the input system.
it's up top in the first code block
Then there needs to be an explicit call to invoke it, here or in the inspector
I aint seeing that
Neither do I see anything regarding any input system tbh
what's with code? ๐
oh its my new inputsystem
using UnityEngine.InputSystem;
public class P_Controller : MonoBehaviour
{
public bool RotChanged;
private void Update()
{
}
void OnRotation(InputValue value)
{
RotChanged = value.isPressed;
}
}```
I have a animation that plays when the parameter, isAttacking, is true. The animation is attached to the object sword. On the enemy game object i want it to be like:
on collision
if collision object = sword && isAttacking = true:
........
I just am stuck on checking whether isAttacking is true, as the code works without that condition
So where are you pressing "D"?
yep! but for some reason it didnt respond ๐ฆ
wha'ts even that? maybe you'd like to share your c# code with us?
this one hahaha
first of all, you can write it like anim.GEtBool("isAttacking") == true
secondly, I guess you do not even need to access gameObject prooerty from collision (in OnTriggerEnter)
Why do some Debug.Logs not collapse?
then, what's wrong? It does not work?
no
There's nothing in here or in the code that suggests you're actually listening for the input, which is what I am asking
Please read the documentation on how to use the new system, especially this: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Actions.html
no? what is that supposed to mean?
Huh? What's the difference apart from the random uppercase E?
ok
oh*
i mean
sorry
I gonna correct it now
it dosent work
@hexed pecan that's my fingers' mistake
first of all, you can write it like anim.GetBool("isAttacking") (without == true)
This is purely syntactic sugar and completely irrelevant on fixing the issue
I know that
I'm not sure if this is the right channel. I'm creating a project template to spin up XR projects faster for my own use. I've followed a couple guides on creating these and I've done everything they say. The template appears in Unity Hub but when I try to actually create a project with it it says it's "not a valid project template". I'd appreciate some help
Then why are you trying to fix the issue with it
what does not work? you cannot decrease the score
yes, when they collide the enemy health does not decrease
it does not work
I was not trying to fix the issue, that was just my suggestion on impoving his/her code before he/she sent the issue
Check that the object has the tag "Sword", then check that there is a collider on it, then check the spelling of "isAttacking". If it still doesn't work, write Debug.Log("Collision detected") above the if statement
What is this script attached to? The player?
try to Debug.Log() each boolean in that code
Yeah, could log the collision.gameObject.tag too
Debug.Log(collision.CompareTag("Sword")); and
Debug.Log(anim.GetBool("isAtacking"));
the enemy
Does the sword have a trigger collider attached?
No need. Fixing the issue is much more important over fixating over the code style of a user, especially since it can just lead to confusion on what exactly the fix was. You should fix the issue, then give a tip on how to write parts of the code better
let it be
If the sword is moving purely via animations, it will likely not register OnTriggerEnter correctly
Hmm... So is the enemy checking if it is colliding with another player's sword?
yes
I feel like the sword should do the checking
needs a little bit of kinematic rigidbody!
I've gotten good results with trigger detection on animated hitboxes
Is this normal behaviour?
Might be Unity just not doing it correctly? You can try a few times and see if it happens randomly?
hey there, i just joined this server hoping to get a bit of help with some C# coding since I basically have little to no knowledge in this area. I'm making a small 2D game for a university project and was wondering how I can make a sprite change when it gets hit once and then disappears when hit again (sorry if this sounds basic, my uni doesnt teach coding and im not a coder at all, more of an artist)
ask this in #๐ปโcode-beginner
ok sure!
Alright. I was wondering if there was a reason. I guess not. Thanks
Ive wondered it too, I just assume its a bug
Aight. I won't make anything of it then
The sword is a child object of the player. When a button is pressed an animation parameter called isAttacking is set to true. while isAttacking is true the animation will play and loop, in which the sword will change in rotation. I have the enemies detecting if they collide with the sword game object. however i want the enemy health value to decrease only when sword and enemy has collided, and isAttacking is true (the attack animation is playing)
Have you checked (with a Debug.Log) that your OnTriggerEnter ever runs?
ive checked, not with the debug log tho.
this code works as intended
however i am struggling to add the isAttacking = true parameter
you can combine boolean conditions in your if statement with &&
(means "and")
i did
Like you did here
didnt work
Did you get an error
define "didn't work"
i dont think im fetching isAttacking properly
it would not subtract from the enemies health
Does it have an animator attached on the same object
And does the animator use a bool called "isAttacking"
Debug.Log is your friend to check the current values of data
i dont quite understand
Your code expects the object to have an Animator component on it, since you are doing anim = GetComponent<Animator>() etc.
i have the enemy health as a public variable so i can see it in the inspector
That's not what I mean
you need to check isAttacking and the tag with debug.log
ahh i see, no the animator component is attached to the sword not the enemy
So you are getting an error
Because anim is null
Cleanest way would be to not fetch any bools from the animator
Just use a bool in your C# script like isAttacking
Then send that bool to the animator, and check that bool when needed
Show how you are currently setting the animator's "isAttacking" bool?
yeah, reading directly from the animator feels weird
in my game, I have Hitbox components that get enabled when the weapon is being swung
doing something similar, like this, would be smart
Is there a way to Debug.Log() the caller of the method?
Debug.Log always prints the whole stack trace already
so you can already see it
okay, thanks for the help
Oh, right
Does what I said make sense?
You would store the isAttacking in a bool, and every time you want to check if the enemy is attacking, you would check that bool instead of getting it with anim.GetBool
It wouldn't help anyway in my case. I might need some help here. For some reason my "change turn code runs twice"
I also don't trust that the animator parameters always change instantly...
I have to look into how the timings work in animator
Could just be the unresponsiveness of the Animator window but I feel like it's a bit sticky still
To add to this... This is the code that runs on console line 2 and three (this method is called TurnEnded()): cs currentCharacter = lastTurns.IndexOf(lowestPossibleLastTurn); Debug.Log($"GM changed turn to {characters[currentCharacter].gameObject.name}"); Debug.Log($"onStartChangeTurn listener count: {onStartChangeTurn.GetPersistentEventCount()}"); onStartChangeTurn.Invoke(); onStartChangeTurn has one listener, which is this method (HandleChangeTurn()): ```cs
public void HandleChangeTurn()
{
StartCoroutine(ChangeTurn());
}
private IEnumerator ChangeTurn()
{
// Start moving the camera to the character
ChangeFollowTarget(manager.characters[manager.currentCharacter].transform);
// Wait for the camera move to be complete
yield return new WaitForSeconds(changeTurnPanWait);
// Handle input
manager.characters[manager.currentCharacter].BeginTurn();
}
public void ChangeFollowTarget(Transform _followObject)
{
vcam.Follow = _followObject;
Debug.Log($"Camera is now following {_followObject}", _followObject.gameObject);
}```
I don't understand how it gets called twice
i think the worst part is that it's just a magic string
does it exist? idk
you will find out at runtime (:
i need a 999 error emoji
that's the Big Boy Error
Thats the closest we have
And both console line 4 and 5 are called by TurnEnded(), but the Debug.Log()s are only called once. How can this be? I am seriously confused now
I'm going insane ๐ญ ๐ญ
I FIGURED IT OUT!!! If I call onStartChangeTurn.Invoke(), CameraController.Instance.HandleChangeTurn() somehow gets called twice. Calling CameraController.Instance.HandleChangeTurn() directly only calls it once. If anyone knows the reason, please let me know
Does onStartChangeTurn.GetPersistentEventCount() not get the number of listeners? What does "persistent" mean in this case?
Not that this answers my question
Can there be duplicate listeners that will count as 1 persistent listener?
This is what I think might have happened
Are you registering listeners in your code? Or just in the inspector?
Persistent listeners are the ones that are serialized in the editor. You can also have listeners added in code that wouldn't count towards this number.
ooh, so that's what you call it
is there any way to make it so when I update my unity editor I don't lose all my script templates and have to recopy them?
Code too. I guess that's why
That explains it
hi,
is it possible to call the begainDrag and Dragging events without actually do the dragging ??
i wanna call the onStartDrag and Dragging without actually clicking or dragging , how do i do that ?
What
Just, call the method from some other code
oh yeah,.. yeah i didnt sleep well last night ๐ im not myself today
anyway thanks a lot ^^
event system?
yea sort of but yea calling the functions actually helps
Is it true that nested if statements are bad?
They can result in bad readability, but how about performance?
performance is not the problem
Good!
i guess you could construct a massive number of nested if statements that takes a little while to navigate
but each one translates to:
- compute a condition
- jump if it's true / false
Alright. And that is no big deal to have a lot of?
You would have to be indenting your code about 10 feet off the right side of your screen before the if statements themselves became a performance liability
It's much more a code readability/maintainability issue
if you have a lot of nested statements I'd probably wonder if things could be coded more efficiently
Good
I don't
Someone told me to be careful of using nested if statements when I first got into coding with Unity. I have always been afraid how it might impact performance of it since then
lol
Right! I saw this on reddit the other night
LOL I saw that recently nice to see people still able to come up with funny versions of the same joke
how many nests are we talking?
5 is the most
Wait inside each other
Like 5 layers
It is pretty complex behaviour, so I think it makes sense
I used switch statements to make it easier to keep track of
I do that too... Well, continue since it's a while true loop in a per-frame-IEnumerator
early return is certainly convenient
many of my functions start with
if (dont)
return;
not to be confused with
if (going_to_crash)
dont();```
void loadFile(string file) {
if (file == null) return;
// stuff
}```
vs
```csharp
void loadFile(string file) {
if (file != null) {
// stuff
}
}```
I do that too, but now that you mention it, there are a couple places where I have done the opposite
and obviously there are things like switch statements which people also prefer over nests(if the situation allows)
switch statements and enums make a good pair
I miss java enums ๐ฆ
Actually no, it wouldn't work
Unless there is a way to just jump out of the parent if statement?
if (somethingThatIsTrue) // This is the parent if statement
{
if (file == null) // exit parent if statement;
LoadFile(file);
}```
I'd say for your example you posted using a method to handle the code would help readability and avoid deep nesting
ie
Hey C# has a goto 
?
if (Input.GetMouseButtonDown(0)) {
if (foo) {
// stuff
}
}```
```csharp
if (Input.GetMouseButtonDown(0)) leftMouseButton();
void leftMouseButton() {
if (foo) {
// stuff
}
}
Woooow! What does it do?
just - do yourself a favor and don't.
It does what you'd expect it to do.
Goes to a line number?
goto a label
it gets a bit of an excessive bad rap
BUT
and that's a 72-point all-caps flaming "but"
it deserves most of said bad rap
it's the most powerful form of flow control: you just...go somewhere
it's the hardest to reason about
you can no longer reason "well, I always do A before I do B"
i have never written a goto in C# and i don't plan to change that, lol
if (a) goto l1
some statements
l1:
some statements
Just nest the bottom part with !=null
if(truething){
if (file!=null) {your code here}
}```
How in the world is a goto the first thing you think about there
it's not there was a discussion of deep nests and readability
I don't think anyone was actually recommending goto
Oh
Ok to reduce nesting then create a new method and use return
For guard clauses
Am I correct in thinking that the "root namespace" property of an ASMdef should put every script in that asm into that namespace?
I don't think it will do anything retroactively.
It might cause newly created scripts in that assembly to get that namespace
unsure
Interesting, I did add it, and rebuilt the .csproj files, but it doesn't seem to copy the root namespace into the .csproj
So that explains that, but I guess that just means "it doesn't work ATM" which is fine, but good to know lol
is it like ti-basic where on every goto call it causes a mem leak?
nah, it's just a very complex operation
an if statement is very simple: it advances to one of two statements
I bet you have. break, continue, return are all goto's
pure JSP is a bitch, most of the time not worth the effort
Is there a best way to display a List in the inspector using the Editor window in a custom editor? I didn't see one in EditorGUILayout
PropertyField will work for lists
can someone help me with my 2d movement, i changed my jump and double jump from update to fixedupdate and now 80% of the time i try/press to jump it won't do it https://gdl.space/emacukupib.cs
Reading input in FixedUpdate is your problem
Input processing goes in Update
Physics goes in FixedUpdate
wdym "they're in a single if statement"
I mean adding forces, setting RB velocities, calling MovePosition, etc. Physics stuff
anything to do with Rigidbodies
yes but the if statement has input that changes the velocity
i think popsikle's concern is that the input checking is used to control the if statement that does the movement
you need to store the player's input and then check it later
You read the input in Update. Save the user's intent to jump in a variable
then consume that intent in FixedUpdate
right
input processing in Update, physics in FixedUpdate
im confused, am i dumb for not knowing how to "read" player input...
you are already doing it
You're already doing it
Input.GetKeyDown
this is reading input
instead of immediately using the result to decide if you want to run an if statement, store it for later.
what i don't get is the storing part
you store tons of stuff already
[SerializeField] private Rigidbody2D rb;
[SerializeField] private float speedMult;
[SerializeField] private float jumpForce;
[SerializeField] private float doublejumpForce;
[SerializeField] private GameObject player;
[SerializeField] Transform GroundCheck;
[SerializeField] LayerMask groundLayer;
[SerializeField] LayerMask nextLevel;
[SerializeField] private float doubleJump = 1;
[SerializeField] private BoxCollider2D trigger;
public bool isGrounded = false;
public bool loadlvl2 = false;
all of these!
wait so im supposed to store input in a variable...
...and then consult that variable later
damn
GetKeyDown simply returns a bool. Like any other data it can be stored in a variable
i feel a bool would be the easiest
yep
That being said you shouldn't store that directly in a variable
huh
you should do:
if (Input.GetKeyDown(KeyCode.Space)) {
userWantsToJump = true;
}```
if you just did userWantsToJump = Input.GetKeyDown(KeyCode.Space); you would end up with the same issue because it will end up getting set to false before FixedUpdate gets a chance to run
so input in Update()
wait so
uuhh
userWantsToJump would be in FixedUpdate right?
it would be used there, sure
no it'd be an instance variable
You'd declare it outside of any method
and use it in both methods
a field!
much like all of these fields you already have
yep
if you declared it as a variable in Update, then it would only exist in Update
and you would get nowhere
Hey so I have a UnityBLE Plugin that works fine in editor on the Mac but when I build and run on mac I get a dll error? What could be wrong?
so this would be in update
and
if userWantsToJump()
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}
?
Well that syntax is a little broken and you also want to consume that intent so don't forget userWantsToJump = true;
== is the comparison operator
it's also redundant
you can just write if (userWantsToJump)
an if statement will accept anything that can be converted to a bool
at this point i think my brain is just broken
bool is very good at converting to bool :p
so
if (userWantsToJump && isGrounded)
{
rb.velocity = rb.velocity + (Vector2 * jumpForce);
isGrounded == false;
}
isGrounded == false; compares isGrounded to false
think carefully about what each line you're writing is doing
= sets it to false?
correct
= is the assignment operator
it stores the right hand side into the left hand side
also, you are still missing one last important part
?
userWantsToJump is still true
ah
it doesn't reset itself
so also userWantsToJump = true;
well, that wouldn't do very much
;/
!isGrounded
...then this won't really change anything, will it?
told you my brain is broken
a useful technique for catching this kind of mistake is to "rubber duck" the code
go through the code and explain what each line does to someone
if you don't have a someone, explain it to a rubber duck!
so isGrounded = false; and userWantToJump = false; in the if statement
That sounds reasonable.
idk why i never thought of doing that
Although, isGrounded should get set to false the next time you check for grounding
well it doesn't seem intuitive
you know what it does, because you're looking at it, and you wrote it, right?
but forcing yourself to actually formulate that into coherent sentences can reveal things you don't really get
it's like me looking at the practice exam and thinking "Yeah that's easy"
but not actually doing the practice exam
makes sense
next time i check for grounding?
well, you need to figure out when you're on the ground again, right?
well doesn't this take care of it? isGrounded = Physics2D.OverlapCircle(GroundCheck.position, 0.15f, groundLayer);
ya
checking for the groundLayer
so, if you leave the ground, that'll set isGrounded to false
once you get out of range of the ground, at least
yep
setting isGrounded later on in FixedUpdate won't really do anything, since the next time FixedUpdate runs, it'll set isGrounded again
so it can be either kept or removed?
yeah
It would be important if you did anything else with isGrounded later on
e.g. if you also had a dodge move that only worked on the ground
so im guessing the script is correct now https://gdl.space/oqofuqazoh.cs
nvm
Hi there, I have a Bootstrap scene as my first scene, and the Game scene as my third scene
so here is a general question on coding an AI. (2D top down) I want the AI to wonder around in a set radius but at random meaning the ai won't just travel a circle but, to point a to point b the randomly select cords a to b inside a set radius and travel to those. i have a raycast for line of site to detect players. I got the raycast working to detect layers/tags which seems fine for now. I have a basic ai movement but in a circle. im not aware of the best ways to go about this. ik this is prob a big question ๐
https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html can be used to select a random point in a circle
guess I need a corutine or some way oh maybe an if statement like if ai reached randomPoint then run the random point and walking again ?
At the highest level you need a state machine basically. You need to track the current destination, and check for if the destination is reached, and then once reached you need to pick a new destination and start over
that could be implemented with coroutines or just with a some conditional statements in Update
okay yea state machine seems out of my league i think idk ๐ conditional statements and if that dont work then ill look into state machine
a state machine isn't anything crazy
very simple
public enum States { Idle, Roaming, Chasing, Etc... }
it's a state (maybe an enum) and some logic for each state
the machine decides 1) what to do based on the current state and 2) if it should switch to another state
ok thanks ill look into it
yea chatgpt is so useful... i feel like its cheat its not exactly what i want but its super close
I have a player character that is in the first scene, the player can revisit the first scene but when this happens another instance of that player spawns. How can I stop this from happening
i think a singleton? new to programming ๐ but its kinda the same thing with gamemanager
private void Awake()
{
//Singleton Pattern
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
this should work ? ๐
thanks, I actually just copied that exact code from chatgpt lol
haha yea ... thats how i got it ๐
haha beginner helping beginner ๐ ... cough chatgpt... got us
DDOL isnt part of the singleton pattern. so you may not need it.
hi,
is there is a direct way to get the canvas corners ?
I can calculate it but if there is a built in way , that would be more convenient
https://docs.unity3d.com/ScriptReference/Canvas-pixelRect.html
then you can get the min and max from that
thanks !
Can someone help me understand how to use occlusion culling on a 2d tile game. I have thousands of tiles for the user to click on to reveal whatโs underneath. And after about 16,000 tile flips, my runtime crashes. I assume occlusion culling is the way to go? The only issue is that I canโt find anything on randomly generated things at runtime.
I would love some guidance on this if anyone knows, just tag me for the response. Thanks Iโm advance
I am not quite sure if this will work for your project because its 2D but you can mess with the CullinGroup API, I think it is mostly for 3D but I guess you should not have major problems on 2D https://docs.unity3d.com/Manual/CullingGroupAPI.html
quick question , which start function fires first , the parent's or the child's ?
It's random and not something you should rely on
thx i used awake on the important stuff just in case
hey, how to make class Item in a public list editable on the editor ?
i added [System.Serializable] before declaring the class Item but it didnt work! , did i forgot to do something
in another script i wrote public List<Item > ItemList = new List<Item >();
and in the Item class script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item: Element
{
public float health;
}
a class that has a some functions , all inherted from monobehaviour and so far no errors
MonoBehaviours do not need to be marked as serializable
they will appear in the inspector as object fields
I have some steps to debug issues like these https://unity.huh.how/programming/serialization
I think zylog is expecting the items to be editable -- as in, they appear as a list of properties, instead of just a reference field
I'm not sure how you'd do that, or if that's even a good idea for MonoBehaviours
it doesn't work like that
If you want a list of editable values then you use a normal serializable class, not a MonoBehaviour
If you need a MonoBehaviour then you can right-click on your object field and select Properties... which will pop out an inspector, allowing you to make edits without changing selection
Inheriting from Monobehaviour is your issue
ive been trying for a while now but i just can't seem to get this door to rotate open naturally, i'm using transform.RotateAround with a position just slightly to the left of the door itself, should be enough that the axis is at the very left of the door. It seems to do this instead:
hmm, I forget if RotateAround cares where the pivot point of the object is
You have it on "Center" right now. Can you switch it to "Pivot"?
animation rigging sounds like a weird choice for a door
ignore my statement, carry on
yes thank you !!
Just fix the object's pivot instead of using RotateAround
just parent it to an object sitting at the point you need the door to rotate around
then do local rotation
Hello there, browising through Job system docs, I found this method JobHandle.ScheduleBatchedJobs() , which apparently should make the initialization of worker threads faster, however the docs dont provide an example of it, so how should I use it?
My current implementation looks like this, but I don't know if that method is actually doing something or If there is a different way for calling that
Switching to Pivot didn't do anything to the actual motion, but it should reveal that the pivot point was at a reasonable spot for the door
or do you mean you did what Praetor suggested?
i keep getting this error 'Item' is missing the class attribute 'ExtensionOfNativeClass'! > where Item is a class
[System.Serializable]
public class Item
{
public float health;
public float amount;
public float power;
}
i just switched to pivot and now local rotation does what i want it to
have you restarted the editor
i'm trying to remember where I've seen this error
but your code looks valid
no , oh could it be an editor bug , interesting.
ah, gotcha -- but do keep in min that changing the mode didn't change how setting localRotation works :p
it just changes the gizmos
I do prefer to leave it on Pivot. I usually put the pivot point in a useful location!
hmm, really?
its because the script might still be attached to an object in game but not monobehaviour now. I had this yesterday
how do i use the pivot point in changing the rotation
ah! that could be it
all that the Pivot/Center toggle does is decide how the scene view gizmos work
it does not change anything else
iiii seee
i understand now ty
just needed to use the transform.position as the pivot in the function call
I'm not sure what to do next? like should i be creating culling groups on Start() or Awake() and spawn them everywhere? do you recomend an y free sources to helpo guide me in the process of learning about culling in unity
that was it , yes ๐ , thanks !!
Good question, I wish I could give you more info, but I have not implemented this yet to give you an idea of what to do Next
ok well thank you for your time ๐ very appreciated
well there are several ways of the top of my head
I guess another approach you can take is loading stuff that is near the player, so you dont actually display the full 16.000 tiles even if you are not seeing them
spatial hash, hierarchical grid @faint hornet
this is a technique used in minecraft for example, where the chunks are only loaded according to the player's view distance
there is no player in the game. its kinda like Shapez.io. have you ever played that game?
I have never :/
have you every played or seen factorio?
internet dying
the whole concept is to narrow down the search for potential collision candidates
in your case its tile rects or whatever sprites you have with the frustum rect
yeah but how do i do that with dynamically generated tiles? they don't move they just are instantiated
whats the difference
I havent played that either, but I just tested Shapez.io and I understand what you mean, however I don't understand why you would spawn 16K tiles
do you have any sort of grid in place?
can i post a picture of my game in here to show you what i mean?
what relevancy has player or pictures
and factorio can be played in playerless mode yes i played it
concepts dont change
you need some sort of spatial structure, be it a 2d array, or something more complex
the blue tile is clicked to create 64 new smaller tiles
once 50+ of these blue tiles are"purchased" you can imagine how many tiles are being rendered off screen... i want to stop rendering all of them but keep the data flowing
have you read anything i said
yes but i don't understand what you mean
ok..
I get this now, you need to apply the concept as @ashen yoke mentioned, spatial hashing
when i look up culling tuts oin youtube for unity all i get is stuff about objects that are already placed in the sceen and ready to be "baked" but i dont have that option because everything is dynamically spawned
that is not related to culling as a concept
that is related to unity's specific implementation of 3d culling
ahh ok
@faint hornet but actually I guess you can make it a bit simpler with the aproach I mentioned, you can consider the camera as the player
a DIY culling system wont differentiate between runtime insertions and editor time
yeah i don't fully understand how to go about coding my own culling script that is efficient..
i mean... yeah i guess? every tile holds it's world position data and is stored in a vector2Int dictionary ?
so basic spatial hash
then the answer is yes!
not familiar with the term spacial hash but ok!
a dictionary is a hash map essentially
so do i need a camera script that handles the rendering of the tiles ?
the key is a hash, an int value
yes i understand what a dictionary is and how to use. but of so a hash is like a dictionary
" a hash is like a dictionary"?
no, dictionary uses hashing to store values, spatial means "in space" or "related to space"
spatial (space) hashing (using hash as a way to store data)
hashing in this case is coverting Vector2Int into an int
anyway
hmm. ok that makes sence. thanks for clearifying
but what do i do from there to create a culling script using the dictionary?
assume instead of V2i dictionary you have a 2d array
you need to find all tiles that intersect this line
public class CullObjects : MonoBehaviour
{
private Camera _camera;
private Bounds _cameraBounds;
private void Start()
{
_camera = Camera.main;
_cameraBounds = new Bounds(_camera.transform.position, new Vector3(_camera.orthographicSize * 2 * _camera.aspect, _camera.orthographicSize * 2, 0));
}
private void Update()
{
foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Cullable"))
{
if (IsInCameraView(obj))
{
obj.SetActive(true);
}
else
{
obj.SetActive(false);
}
}
}
private bool IsInCameraView(GameObject obj)
{
Renderer renderer = obj.GetComponent<Renderer>();
if (renderer == null)
{
return false;
}
Bounds bounds = renderer.bounds;
return _cameraBounds.Intersects(bounds);
}
}
wowuld this work?
yes
so i put cullable tag on the big tiles and the small tiles and it should work?
i dunno i give up
you are trying to solve optimization problem by bruteforcing it with the least optimized approach
its the same as being given a bag of coins and told to count them and you start counting them one by one
so this script is not optimized is what you are saying?
and btw i was readying you previous messages and i saw your red boxes you made. if you want to explain more of that i would love to hear it
private void Update()
{
foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Cullable"))
{
each frame you call the least efficient method in unity to get objects
it allocates a new massive array each frame
yeah that is not very optimized
you then iterate through all of those
and you switch game object active state
which disables the whole object not just rendering, calling OnEnable/Disable on each component
but it wouldnt be that bad if the find objects tag didn't look at every object in the scene...
but only the ones in frame
ahhh i see. ok contiue explaining lol
what is this
the whole concept is to narrow down the search for potential collision candidates
right. i understand that. but i'm just not understanding how you want me to actually narrow it down?
now we have a 2d array in place, each index in that array is a list
@faint hornet basically what cache is saying is why it is extremely ineficient to look for all GameObjects in the scene, thats where spatial hashing takes place, it only executes operatation within each grid cell instead of the whole scene
like i get that you want me to find the stuff nearest to the camera to simplify by alot but how?
each "cell" of this array contains tiles inside of the cells
so in the line example, we
- find out which cells the line intersects
- get all the tiles in those 2 cells and test them for collision
this narrows down the search from 1000s of objects to 200
yeah so i have two dictioanrys . one that holds all the large tiles. (parents) and one that holds all possible smaller tile (child)
that is not enough
a barebones dictionary doesnt optimize anything by itself
you need a grid
do we do this by using a raycast?
there are algorithms online for line grid intersections but yes that is raycast in essense
ok understood but wait slow down.. so line grid intersections.. shoudl i create my own line grid? or use unitys build in world space grid.. (which is what i'm currently using obvi)
forget about the raycast
ok
its just there for an example of "scenario in which you need to find something"
can be just a point
so what does the line intersect?
in the picture
it intersects two parents tiles
buckets. ok
and buckets are what store them
i have a script that holds these "buckets" i call them chunks
now instead of Dictionary of your tiles, you will have a dictionary of buckets
each bucket can be simply a list
i do have a dictioanry of these buckets.. i have a chunk dictionary
then you have the problem already solved
all you need is to intersect the camera frustum with the buckets
ok so if the bucket is intersected. then i enable all children in the bucket?
yep
ok so i want to probably put a frustrum just outside of the cameras view..
all you need is some simple for loop that starts at the frustum min, and ends at frustum max point
to determine which buckets to check
is the frustrum a volumetric thing or just a perimeter thing
you can further optimize it
by testing each object in each bucket individually
you can play around with bucket dimensions
ie not 10*10 tiles, but 4*4
but wait.. question
what do you mean by this
i currently have the code remove the collisions on the bucket once they are purchesed.. is this an issue?
no
ok..
and what i meant by this is if that blue square was bigger.. lets say the blue line intersected 8 tiles but it is not intersecting the central square.. will that be an issue
this is the anser to this question
those are 2 different examples
one was with imaginary line, one with imaginary camera
i know... but what i'm asking is if it is volumetric
i dont understand what you mean by volumetric
you mean if the camera frustum is 3d?
you have a 2d game so for all intents you can think of it as 2d rect
ok so you say the frustrum is a line that intersects the grid... but what if it doesnt intersect something withing the central area of the frustrum.. would it consider that to not be an "intersection"
ok so it is area.. not an outline
ok so ya all the yellow area is part of the "intersection" right?
nope thats just the bottom of the frustum
better call it overlap
ok sure. but thats what i meant by volumetric
in 2d camera frustum is "flat" it looks like a straight box, because you have orthographic projection
so you get just a rectangle
you can use Rect
theres even a camera.rect property
sure but even in 2d space there are layers and the 2d frustrum is still and infinitly long rectangle capturing all layers in front of the camera
tho thats normalized
there is no depth, the layers are simply a render order customization
ok
well alright techincally there is depth but its unrelated to this
you are working with a 2d bucket grid
you are overlapping 2d rectangle
to find buckets
so is this more like what you are talking about?
public class CullObjects : MonoBehaviour
{
private Camera _camera;
private Plane[] _frustumPlanes;
private void Start()
{
_camera = Camera.main;
_frustumPlanes = GeometryUtility.CalculateFrustumPlanes(_camera);
}
private void Update()
{
foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Cullable"))
{
if (IsInFrustum(obj))
{
obj.SetActive(true);
}
else
{
obj.SetActive(false);
}
}
}
private bool IsInFrustum(GameObject obj)
{
Renderer renderer = obj.GetComponent<Renderer>();
if (renderer == null)
{
return false;
}
Bounds bounds = renderer.bounds;
return GeometryUtility.TestPlanesAABB(_frustumPlanes, bounds);
}
}
camera.bounds to Rect will suffice
this is still inefficient becasue it's still checkign every object in scene right?
is this better?
public class CullObjects : MonoBehaviour
{
private Camera _camera;
private Plane[] _frustumPlanes;
private HashSet<GameObject> _visibleObjects = new HashSet<GameObject>();
private void Start()
{
_camera = Camera.main;
_frustumPlanes = GeometryUtility.CalculateFrustumPlanes(_camera);
}
private void Update()
{
HashSet<GameObject> oldVisibleObjects = _visibleObjects;
_visibleObjects = new HashSet<GameObject>();
// Check all renderers within camera frustum
foreach (Renderer renderer in GetVisibleRenderers())
{
GameObject obj = renderer.gameObject;
if (!oldVisibleObjects.Contains(obj))
{
// Object is newly visible
obj.SetActive(true);
}
_visibleObjects.Add(obj);
}
// Hide all previously visible objects that are no longer in camera frustum
foreach (GameObject obj in oldVisibleObjects)
{
if (!_visibleObjects.Contains(obj))
{
obj.SetActive(false);
}
}
}
private IEnumerable<Renderer> GetVisibleRenderers()
{
// Get all visible renderers within camera frustum
Collider[] colliders = Physics.OverlapSphere(_camera.transform.position, _camera.farClipPlane);
foreach (Collider collider in colliders)
{
Renderer renderer = collider.GetComponent<Renderer>();
if (renderer != null && GeometryUtility.TestPlanesAABB(_frustumPlanes, renderer.bounds))
{
yield return renderer;
}
}
}
}
is this ai generated?
yes lol
im done
i'm not using it lol i'm just using it for learning purposes. obviously becasue my code will be much more specific that this
but i'm asking if this is more or less how you would create the script
seriously lol not one line of code in my game is ai generated. just fyi. i use it to learn. and with your input and the ai's input i'll get a much better understanding of a concept. it's a tool
void Update()
{
Rotating();
}
void Rotating()
{
if (controller.RotChanged)
changeDirection = !changeDirection;
if (changeDirection)
transform.Rotate(0, 0, RotSpeed * Time.deltaTime);
else
transform.Rotate(0, 0, -RotSpeed * Time.deltaTime);
}
```
Hi sorry, erm.. this is using the new input system, when i use the old one with the Input.Getkey etc, it works for toggling which im aiming to do here. But now i use the new input system and the toggling "sometime" works, its not consistent. anyone have any advice? ๐ฆ
It might be resetting to false within the same frame.๐ค
Just set a bool in the input callback.
It's unclear from your code how you're processing the input
What is controller.RotChanged and how does it work?
oh input callback? ty for that clue. i will try search on that
public class P_Controller : MonoBehaviour
{
public bool RotChanged;
private void Update()
{
}
void OnRotate(InputValue value)
{
RotChanged = value.isPressed;
}
}```
this one hahaha
it is for my new input system
This is just checking if it's pressed
so it's going to happen every frame while the button is pressed
combined with your other code this means you will change directions every frame while the button is pressed
so you're essentially flipping a coin
Unfortunately the "Send Messages" mode of PlayerInput isn't conducive to handling a typical "button" input since InputValue has no "WasPressedThisFrame" functionality. The most straightforward options here are:
- checking if it just became pressed this frame by comparing it to last frame's isPressed value
- switching to Unity Events mode and checking for the context being
performedin the callback
Currently you have the equivalent of Input.GetKey when what you want is Input.GetKeyDown, make sense?
ahh i see. thanks!! you're the second person to advice on callback too, means i will look into that firstly. then if im still lost, i will go to your first option ๐
man... new input system is such a headache!
YES! like press once till i raise up and press again
hahaha
It's... definitely more complex. Once you get the hang of it it's much more powerful though
//StatClass ScriptableObject Interfaces
public interface IEntityStatsSO {}
public interface IPlayerStatsSO : IEnemyStatsSO {}
//StatClass Interfaces
public interface IEntityStats<out SO> where SO : IEntityStatsSO
{
public void Assign(IEntityStatsSO StatsSO);
public SO StatsSO { get; }
}
public interface IPlayerStats : IEntityStats<IPlayerStatsSO>{}
//StatClasses
public class EntityStats<SO> : MonoBehaviour, IEntityStats<SO> where SO : IEntityStatsSO {};
public class PlayerStats : EntityStats<IPlayerStatsSO> {};
//IEntity Interface
public interface IEntity<Stats> : IObject where Stats : IEntityStats<IEntityStatsSO>
{
public Stats StatsManager { get; }
}
//IPlayer Interface
public interface IPlayer : IEntity<IPlayerStats> {}```
So I went back to my stat classes and decided to split them up a bit between the enemy and player, while keeping the base class non-abstract for entities such as destructibles. Now, for some reason I keep falling into this spider web of interfaces when I try to pair the derived type of my base class ``EntityStats`` with a similar scriptable object type. Ex. ``PlayerStats`` takes in a derived SO type of ``PlayerStatsSO``, and ``EnemyStats`` takes in a derived SO type of ``EnemyStatsSO``. I believe I have it somewhat working, but I run into the problem that when I try to assign these types to a shared interface of ``IEntity`` which I use throughout my project using ``GetComponent``. I run into the issue of now having to provide types for generic parameters. I don't believe I am doing this correctly as at that point in the code I do not care, or what the specific type to be returned, but the base type.
Perhaps I'm going about this the wrong way and that I should ditch this concept of covariance. Has anyone a better solution I should consider? My other idea is to ditch the generics all together and use the base Assign(EntitySO) function to take only in base type SOs which I would override and check in the derived class. And, probably create a function like GetType() to return the type contained.
can someone tell me if something looks off here? i feel like my pc is struggling and i'm not sure if these levels are ok? its a 2d tile based game with probably a total of 5k game objects in scene atm..
there is no audio. no animations no nothin happing other than rendering and scripts... is there something i'm missing here?
expand it and see which scripts are taking up a lot of the time?
it seams to be awake functions and start methods
check whats consuming those 3ms, expand the tab
there is a percentage indicator on the side, it will tell you exactly what causes it
Ahh, thats just Unity UI, nothing wrong with your code
well how do i make it more efficient?
wait, if it's unity UI then it shouldn't allow them to look at it unless they change to editor mode in the profile, but they're in play mode
should i try building it out and see if it's still not performing well?
i just don't understand why it's so laggy and my frames drop below 60. but normally im at like 200+ fps
UI by default takes a fairly low percentage on the profiler, I cant really tell on how to optimize this
can anyone please help me, im really struggling
I have no idea if Unity UI toolkit really performs better than unity canvas
i want to make my object move using the joystick inputs on oculus quest 2 (xr origin) and i dont know how to do it
i also want the camera to follow the object
Hmmm, then it is not caused by UI, there is something else going on
but i'm not using canvas???
in the profiler, whenever your game lags, it makes an spike in the profiler which you can inspect
you dont have UI in your game?
i mean barely anything rn. i just have alot of sprite renders and box colliders
what are you doing with the UI?
i have one canvas and it basicly does nothing
As I said, Unity UI by default updates the canvas no matter how complex it is
well what's nothing?
also as i mentioned, there must be something else going on
well clearly there's something going on with the canvas
I suggest you enable garbage collector checkbox
i'll turn it off completly. and see what happens
yea this has caused a ton of problems for me in the past. It couldn't handle creating/destroying a handful of objects every like 10 seconds. Changing to incremental fixed it.
same here, using incremental CG fixed my stuttering issue in the past
just curious, since your project loads a massive amount of tiles, how much time does it take to generate all those tiles?
look i turned off my canvas object and its still running??
Thats really weird
i don't like hearing those words lol
but also, I noticed you have 3K batches, that's way too high
Lmao, at this point I have no idea of whats going on
yeah i do. thats correct. the batches are high
how do i reduce that? with culling right?
Yes, culling, frustrum culling or anything that reduces the amount of objects rendered at one place
there's multiple ways to reduce drawing calls, batching, if they're the same, culling etc.
batching sounds good in your case?
apart from frustrum culling
ok so i have a culling script on my main camera that doesnt seem to be making a difference in it.
from your screen most of this time is rendering so...
not good. it's just true and i want to reduce it. there are tones being rendered outside of camera range and my cullign script doesn't seem to make a diffference
batching makes a difference way before all that, so it's good.
but yes if if you don't have any frustrum culling then do it, since it's a must?
i do have a frustrum culling. its just not working ro something.. i dont understand it
Consider reading through this - https://docs.unity3d.com/Manual/OcclusionCulling.html
if it's not working it doesn't mean it's not the solution.
but share code somewhere correctly, and following rules
i have already read this
if you still see objects outside camera view then it means your code is not working
yeah i was looking in the scene window and the object were stiull ebing rendered..
share your culling code, maybe someone can tell you the right way
public class CullObjects : MonoBehaviour
{
private Camera _camera;
private Plane[] _frustumPlanes;
private HashSet<GameObject> _visibleObjects = new HashSet<GameObject>();
private void Start() {
_camera = Camera.main;
_frustumPlanes = GeometryUtility.CalculateFrustumPlanes(_camera);
}
private void Update() {
HashSet<GameObject> oldVisibleObjects = _visibleObjects;
_visibleObjects = new HashSet<GameObject>();
foreach (Renderer renderer in GetVisibleRenderers()) {
GameObject obj = renderer.gameObject;
if (!oldVisibleObjects.Contains(obj)) {
obj.SetActive(true);
}
_visibleObjects.Add(obj);
}
foreach (GameObject obj in oldVisibleObjects) {
if (!_visibleObjects.Contains(obj)) {
obj.SetActive(false);
}
}
}
private IEnumerable<Renderer> GetVisibleRenderers() {
Collider[] colliders = Physics.OverlapSphere(_camera.transform.position, _camera.farClipPlane);
foreach (Collider collider in colliders) {
Renderer renderer = collider.GetComponent<Renderer>();
if (renderer != null && GeometryUtility.TestPlanesAABB(_frustumPlanes, renderer.bounds)) {
yield return renderer;
}
}
}
}
this isn't mine btw. it's ai generated and i'm trying to get it to work so i can optimize it after and talor it to my game
also if your objects have a material, make sure to enable gpu instancing on them
but this code is't throwing any errors
ever thing has a material but its the default urp lit material. how do i enable that?
you click on those objects shaders and scrolling down and check gpu instancing
i can't make changes to it
Wdym "if"? Without a material it wouldn't be rendered.๐
but your code has so many issues i can't guess and no one can so
make a custom material, so you can enable gpu instancing
maybe read before?
but anyway that's not even the issue at all
what doe sgpu instancing do ? allow the frustrum culling to work?
why the fuck are you talking about material issues when talking about frustrum culling
you goddamn madlads
because im a fucking idiot trying to figure shit out
that's your issue
keep in mind material do make draw calls...
but everyone's trying to tell shit, they do.
but read further
yeah and im asking for help. if you don't want to help, thats cool.
he says it doesn't even work
Is that frustum culling?
GPU instancing draws multiple meshes in a single drawcall if they have the same material
so this will only draw call once instead of 5000 times if i turn it on?
Unity has frustum culling by default, so I don't see the point of what you're doing @faint hornet
i did notice batching jumping up and down without the script on it. i guess i though there would just be a more effecient way of frustrum culling to overide it
not really, it does it by groups, I dont really know how many objects it groups together in a single draw call, but it helps a lot
If it's jumping up and down, there must be some other reason to it. Unity already does efficient frustum culling. Anything you'd do manually would only make it worse.
now that's helping
*would involve overhead in addition to unity frustum culling.
gpu instancing is bs unless they all do the same movement at the same time or behave the same anyway
@faint hornet what are you trying to do?
he even sent a graph that showned cpu wasnt in a need of "optimization"
apparently he runs immense amount of tiles
he needs to optimize rendering issues
i'm trying to optimize my game. and i think i'm rendering too much. maybe its all the instantiations im using..
if it's tiles tho i'd run chunkes
Instantiations are not part of rendering.
I've found the screenshot of your profiler. It looks like you're within the 16ms budget. Is that not enough?
i have chunks
its not enough becasue i have only just begun and im already using to much. i will be rendering much more later in development
this code won't work and is also very ineficient, you are running a foreach each frame and I think the last confitional at GetVisibleRenderers wont work
Well, then explore the rendering and see what takes most CPU time.
then it's either unavoidable if you do it correctly.
or the chunks are too high?
rendering is always extensive when you want too much of them?
also as storm and dlich said this code isn't needed
here is my new stats after changing materials to gpu instancing..
3k batches is a lot...
the way to optimize rendering is only three way sided,
batching,
culling,
render calls?
Use the frame debugger to figure out why you have them in the first place.
ie lessen lightings any calls required etc
perhaps your game use 2d lighting from urp?
you could lessen the pyramid size of bloom
or remove it all
@faint hornet how many child items do your chunks have
so many things for so many projects we can't guess
can you select a chunk and show us the outline like this
64 children objects drawing all faces?
or only foreseeable faces
so looks like this... let me get a picture
What's all the "purchase" and "xxxx amount" meshes?
that wont apply here, its a tile map, not a 3D model
it's tmp, should i disable those?
this pic doesn't show us anything apart from bad eyepics
That can't possibly be 3k batches..?
im not using a tile map
my bad you're true yes
And your hierarchy is almost empty...
Wait......
terraria 2023
Oh it's a tile prefab
im listening lol
So, we were talking before about why canvas was updating on the profiler even when you disabled it
your tiles use Rect component, and rect is part of canvas
I would change it for a sprite, so it uses Transform instead
I mean a tile prefab
ok ill try that
why
no its not UI
i mean rect is UI part
it's not UI but having a rect makes it render as UI
ok let me try changing that'
he should have a Transform instead of a rect, that can be fixed by using a sprite component
should i make all the siblings transform and leave the parent a rect?
Sprite render *
yes but that's not made unless you make a ui object no?
Hmmm, the parent is only a container, so just go with transform
im using grid layout groups.. is that an issue too?
not really, you can manually swap a transform by a rect
i like the rect transform better
Ah, thats what made your transform a rect
and would never be useful in gameplay feature
grid layout is part of UI
I guess this component is the replacement for that
I have never used it so I cant tell you how it works or even if im right
just guessing here
Why?
@faint hornet keep this in mind
Yes, grid is used for tilemaps usually.
At this point I don't understand why unity tilemaps are not being used..?
i like it more becasue it's easier to use
but it's not made for it at all it's your issue there
to the point no one guessed it
trust me
when i take all those rects off it makes all the instatiations spawn in the same spot instead of on the grid
no
it's way behind that
a game engine is made to be used how it's made
and optimised to be use like that
if you go against it it will never go well
you have to consider that easier thinks are not always suitable and as dlich said, it would be even better if you use tilemaps
What you're doing now is kinda like using your sock instead of a hat. Sure, you can do it, but your head is gonna hurt.
lol
it's funny but exactly what i meant
you're hitting yourself seriously
it may seem harder, but in the long way easier, and way better
and optimised as it should be
And seriously, it feels like you skipped a few steps on your game dev journey. You're trying to create a nuclear bomb before you even know how a wheel works.
UI is for UI, as much as you wouldn't use coroutine for gameplay features
what if my game is kind of like a ui based game? all teh tiles will be clicked at some point
Nothing about it is ui
because that's how anyone would think about it
you would pinpoint where your click with it's api
so the reason why im not using a tile map is becasue it doesn't seem like a good idea for my game but then again i don't know to much about tile maps and the little i do makes it seem like it's not the right fit
and where it is with your click
Hello everyone, I am working on an enemy ai which I have already added patrolling, chasing, and attacking to by using navmesh, but recently I have been trying to add a dash/charge attack and have no idea on how to go about it. I still don't have my head wrapped around physics in unity and was just hoping someone can at least give me a way about solving this issue. Help would be really appreciated, thank you.
all i want to do is randomly generate massive amounts of tiles and have it render properly. like as if minecraft only had one plane and was 2d.
my guess is your guess is wrong, because of biases from elsewhere.
but let the engine guide you, and click where it is. the simpler it is when you're beginning the better it is, once you'll get issues tell us
but arnt tile map tiles only images/sprites ? or are they game objects?
the unity engine is really simple to get, even though it gets time, you'll get there, but the correct way is harder as we say
tilemaps are things given to use by the engine, so optimised for it behind the scenes
as much as UI is the same for it's own correct design
so if you go off way it's all wrong?
i'm not sure if i'm "on point" in my english but i'm trying my best, since i'm french
UI means user interface, etc.
unity can't give us tools to "do what we want" it needs to be specific
if you go off road you're already wrong in your thinking?
@warm oasis so, answer me this. can i randomly generate chunks on a tile map and then have randomly generated tiles within the chunk to be on another tile map and then have all the children in all chunks be apart of the same tile map?
you can do this on a tilemap really fine
they are sprites essentially
there's lots of tutorials "tilemap" wise or sprites, or even 3d
yeah, sure thing
i don't want it to be sprites only. i want game objects that hold data and multiple things
you are confusing something
tilemap is kind of more recent so i agree there's less examples
but it's still possible logic wise
Everything in Unity that can be clicked in inspector is basically a GameObject
even though in term of tech it's quite old
this part is the GameObject
we would all be quite happy to help you realise it
You can store your data separately. You're thinking backwards.
ok what i mean tho is i want each tile to be a package of data containing multiple things. not just an image representation of the data
make a struct of it then
i feeel like i need to take a college course on this. there are just too many posibilites as a beginner
does anyone know how to fix this? (it happened when i downloaded post processing)
honestly yes, but even so you would need help to get quite there "on the good way in the end" start with this
study every c# course, then game design pattern, and go forth
but you're welcomed to ask anytime ๐
awesome thank you
just, remember any framework, game engine, you can't go against it