#archived-code-general

1 messages ยท Page 82 of 1

leaden ice
#

not in Unity

heady iris
#

yes, and if you were to somehow destroy the object while still holding a reference to it, this would crash your game

hollow hound
#

But unity has memory allocated for this object, I can even return it back to scene with all previous state it has.

leaden ice
heady iris
#

the C# runtime will not get rid of the object until all references to it are gone

leaden ice
#

all you have to do is myReferenceToTheObject = null;

#

and it goes away

#

or remove it from whatever list or collection it's in

hollow hound
heady iris
#

again: what is the problem you are trying to solve here?

#

what is wrong that needs to be made right?

leaden ice
#

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?
hollow hound
heady iris
heady iris
#

It's not a state that the C# runtime ever wants to be in

leaden ice
heady iris
#

what if that memory gets re-allocated by somoene else?

#

now you're stomping all over some random object's data

leaden ice
#

Also where possible it's a MissingReferenceException in Unity

hollow hound
#

Hmm, I think I get it.

heady iris
#

this is completely forbidden, by design

#

if you want the object to go away, get rid of all references to the object

hollow hound
#

Thanks for the explanation.

heady iris
#

you could absolutely do this in C++ or some other unmanaged language

#

but then you'd be left with dangling pointers

hollow hound
#

Hmm
Can't it just check all references to this object and rewrite this reference to null?

leaden ice
#

very slow

heady iris
#

it would also be very surprising

leaden ice
#

it would have to search the entire memory of the application to find those references

heady iris
#

a reference-counting GC might not know exactly where the references are

leaden ice
#

or maintain some data structure indexing all references which would itself take a lot of memory and be slow to maintain

heady iris
#

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.

heady iris
leaden ice
#

Regardless Destroy is not even part of C#

#

and certainly wouldn't be hooking into low level C# things

heady iris
#

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

hollow hound
#

Hmm, I understood
Thanks for the answers

heady iris
#

no prob (:

#

it is good to be curious about how all of this stuff works

polar marten
#

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

heady iris
#

at least it has smart pointers now

polar marten
#

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

heady iris
#

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

hollow hound
#

So, is there a way to somehow check all references to destroyed object to know where I forgot to clear my reference?

heady iris
#

Python has facilities for that. I don't think C# has a convenient way to do it.

scarlet juniper
polar marten
#

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

leaden ice
#

it should be fairly obvious

polar marten
# hollow hound So, is there a way to somehow check all references to destroyed object to know w...

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

solemn raven
#

hi,
is it possible to call the begainDrag and Dragging events without actually do the dragging ??

polar marten
#

you can use ExecuteEvents to call any handler, however the state of the pointer event data will be wrong

solemn raven
polar marten
#

there's also OnInitializePotentialDrag if you want to intercept the logic event system uses to decide whether something is a click or drag

balmy herald
#

actually is json manifests count as code?

#

i think thats the stupidest think ima ask today

polar marten
balmy herald
#

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

rocky jackal
#

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

leaden ice
#

which it hasn't

#

re-read the error

rocky jackal
#

then its not been assigned

leaden ice
#

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>();

rocky jackal
#

thank you

leaden ice
#

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

dapper hinge
#

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

ocean river
#

.
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.

leaden ice
leaden ice
wide fiber
#
---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 ๐Ÿ˜ฆ

thin aurora
wide fiber
# thin aurora I'm not seeing any input everywhere, I don't see `RotSpeed` being assigned, I do...

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);
    }
thin aurora
#

So my only guess is you're not even checking if you're pressing it

#

What is P_Controller?

heady iris
#

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

polar marten
thin aurora
#

I aint seeing that

#

Neither do I see anything regarding any input system tbh

wide fiber
# thin aurora What is `P_Controller`?

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;
    }
}```
heavy lynx
#

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

thin aurora
wide fiber
gray mural
wide fiber
gray mural
# heavy lynx

first of all, you can write it like anim.GEtBool("isAttacking") == true

gray mural
# heavy lynx

secondly, I guess you do not even need to access gameObject prooerty from collision (in OnTriggerEnter)

rustic ember
#

Why do some Debug.Logs not collapse?

gray mural
heavy lynx
#

no

thin aurora
# wide fiber this one hahaha

There's nothing in here or in the code that suggests you're actually listening for the input, which is what I am asking

gray mural
hexed pecan
gray mural
#

oh*

#

i mean

#

sorry

#

I gonna correct it now

heavy lynx
gray mural
#

@hexed pecan that's my fingers' mistake

#

first of all, you can write it like anim.GetBool("isAttacking") (without == true)

thin aurora
dusky glen
#

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

thin aurora
#

Then why are you trying to fix the issue with it

gray mural
heavy lynx
#

it does not work

gray mural
rustic ember
# heavy lynx

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

hexed pecan
gray mural
hexed pecan
#

Yeah, could log the collision.gameObject.tag too

gray mural
#

Debug.Log(collision.CompareTag("Sword")); and
Debug.Log(anim.GetBool("isAtacking"));

heavy lynx
rustic ember
thin aurora
hexed pecan
#

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?

hexed pecan
#

I feel like the sword should do the checking

heady iris
#

I've gotten good results with trigger detection on animated hitboxes

rustic ember
thin aurora
silver jay
#

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)

silver jay
#

ok sure!

rustic ember
hexed pecan
rustic ember
heavy lynx
#

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)

hexed pecan
heavy lynx
#

this code works as intended

#

however i am struggling to add the isAttacking = true parameter

leaden ice
#

(means "and")

heavy lynx
#

i did

hexed pecan
heavy lynx
#

didnt work

hexed pecan
#

Did you get an error

leaden ice
#

define "didn't work"

heavy lynx
#

i dont think im fetching isAttacking properly

heavy lynx
hexed pecan
#

And does the animator use a bool called "isAttacking"

leaden ice
heavy lynx
hexed pecan
heavy lynx
leaden ice
#

you need to check isAttacking and the tag with debug.log

heavy lynx
hexed pecan
#

Because anim is null

heavy lynx
#

ah isee

#

how can i go about fixing this?

hexed pecan
#

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?

heady iris
#

yeah, reading directly from the animator feels weird

#

in my game, I have Hitbox components that get enabled when the weapon is being swung

heady iris
rustic ember
#

Is there a way to Debug.Log() the caller of the method?

leaden ice
#

so you can already see it

heavy lynx
#

okay, thanks for the help

rustic ember
hexed pecan
# heavy lynx okay, thanks for the help

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

rustic ember
#

It wouldn't help anyway in my case. I might need some help here. For some reason my "change turn code runs twice"

hexed pecan
#

Could just be the unresponsiveness of the Animator window but I feel like it's a bit sticky still

rustic ember
# rustic ember It wouldn't help anyway in my case. I might need some help here. For some reason...

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

heady iris
#

does it exist? idk

#

you will find out at runtime (:

#

i need a 999 error emoji

#

that's the Big Boy Error

hexed pecan
#

Thats the closest we have

rustic ember
#

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

leaden ice
late lion
heady iris
#

ooh, so that's what you call it

radiant marten
#

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?

rustic ember
solemn raven
#

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 ?

gray thunder
#

What

simple egret
#

Just, call the method from some other code

solemn raven
solemn raven
#

yea sort of but yea calling the functions actually helps

rustic ember
#

Is it true that nested if statements are bad?

#

They can result in bad readability, but how about performance?

heady iris
#

performance is not the problem

rustic ember
#

Good!

heady iris
#

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
rustic ember
#

Alright. And that is no big deal to have a lot of?

leaden ice
#

It's much more a code readability/maintainability issue

radiant marten
#

if you have a lot of nested statements I'd probably wonder if things could be coded more efficiently

rustic ember
#

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

radiant marten
#

you'd want to avoid a situation like this:

heady iris
#

lol

rustic ember
#

This is more like it lol

#

Nice and readable

heady iris
rustic ember
radiant marten
# heady iris

LOL I saw that recently nice to see people still able to come up with funny versions of the same joke

radiant marten
rustic ember
#

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

radiant marten
#

I personally just stop the block with a return

#

for most of my checks

rustic ember
#

I do that too... Well, continue since it's a while true loop in a per-frame-IEnumerator

heady iris
#

early return is certainly convenient

#

many of my functions start with

#
if (dont)
  return;
#

not to be confused with

if (going_to_crash)
  dont();```
radiant marten
#
void loadFile(string file) {
  if (file == null) return;
  // stuff
}```
vs
```csharp
void loadFile(string file) {
  if (file != null) {
    // stuff
  }
}```
rustic ember
#

I do that too, but now that you mention it, there are a couple places where I have done the opposite

radiant marten
#

and obviously there are things like switch statements which people also prefer over nests(if the situation allows)

heady iris
#

switch statements and enums make a good pair

radiant marten
#

I miss java enums ๐Ÿ˜ฆ

rustic ember
#

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);
}```
heady iris
#

that suggests you need to change your design

#

you're asking for a goto

radiant marten
#

ie

leaden ice
rustic ember
radiant marten
#
if (Input.GetMouseButtonDown(0)) {
  if (foo) {
    // stuff
  }
}```
```csharp
if (Input.GetMouseButtonDown(0)) leftMouseButton();

void leftMouseButton() {
  if (foo) {
    // stuff
  }
}
rustic ember
leaden ice
#

It does what you'd expect it to do.

rustic ember
#

Goes to a line number?

fervent furnace
#

goto a label

heady iris
#

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

fervent furnace
#

if (a) goto l1
some statements
l1:
some statements

rustic ember
#

I see

#

I'm not doing that

cerulean oak
#
if(truething){
        if (file!=null) {your code here}
}```
#

How in the world is a goto the first thing you think about there

radiant marten
#

I don't think anyone was actually recommending goto

cerulean oak
#

Oh

#

Ok to reduce nesting then create a new method and use return

#

For guard clauses

royal sable
#

Am I correct in thinking that the "root namespace" property of an ASMdef should put every script in that asm into that namespace?

leaden ice
#

It might cause newly created scripts in that assembly to get that namespace

#

unsure

royal sable
#

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

waxen burrow
heady iris
#

an if statement is very simple: it advances to one of two statements

knotty sun
heady iris
#

well, I should say, explicit gotos :p

#

they are all, indeed, jump statements

knotty sun
reef lagoon
#

any1 know?

#

there isnt any win64_nondevelopment in folder

hexed oak
#

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

leaden ice
junior pollen
#

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

leaden ice
#

Input processing goes in Update
Physics goes in FixedUpdate

junior pollen
#

how can i seperate those...

#

they're in a single if statement

leaden ice
#

wdym "they're in a single if statement"

junior pollen
#

wait what do you mean by the physics

#

like the Physics2D?

leaden ice
#

I mean adding forces, setting RB velocities, calling MovePosition, etc. Physics stuff

#

anything to do with Rigidbodies

junior pollen
#

yes but the if statement has input that changes the velocity

heady iris
#

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

leaden ice
#

then consume that intent in FixedUpdate

junior pollen
#

right

leaden ice
#

input processing in Update, physics in FixedUpdate

junior pollen
heady iris
#

you are already doing it

leaden ice
#

Input.GetKeyDown

#

this is reading input

heady iris
#

instead of immediately using the result to decide if you want to run an if statement, store it for later.

junior pollen
#

what i don't get is the storing part

heady iris
#

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!

junior pollen
#

wait so im supposed to store input in a variable...

heady iris
#

...and then consult that variable later

junior pollen
#

damn

leaden ice
junior pollen
#

i feel a bool would be the easiest

leaden ice
#

That being said you shouldn't store that directly in a variable

junior pollen
#

huh

leaden ice
#

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

junior pollen
#

so input in Update()

#

wait so

#

uuhh

#

userWantsToJump would be in FixedUpdate right?

heady iris
#

it would be used there, sure

leaden ice
#

no it'd be an instance variable

#

You'd declare it outside of any method

#

and use it in both methods

heady iris
#

a field!

heady iris
junior pollen
#

yep

heady iris
#

if you declared it as a variable in Update, then it would only exist in Update

#

and you would get nowhere

flint sierra
#

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?

junior pollen
#

and
if userWantsToJump()
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
isGrounded = false;
}

#

?

leaden ice
junior pollen
#

syntax is kinda broken... if (userWantsToJump = true)*

#

so that would work?

heady iris
#

still broken

#

= is the assignment operator

junior pollen
#

==

heady iris
#

== 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

junior pollen
#

at this point i think my brain is just broken

heady iris
#

bool is very good at converting to bool :p

junior pollen
#

so

#

if (userWantsToJump && isGrounded)
{
rb.velocity = rb.velocity + (Vector2 * jumpForce);
isGrounded == false;
}

heady iris
#

isGrounded == false; compares isGrounded to false

#

think carefully about what each line you're writing is doing

junior pollen
#

= sets it to false?

heady iris
#

correct

#

= is the assignment operator

#

it stores the right hand side into the left hand side

junior pollen
#

why did i think it was the opposite

#

damn

heady iris
#

also, you are still missing one last important part

junior pollen
#

?

heady iris
#

userWantsToJump is still true

junior pollen
#

ah

heady iris
#

it doesn't reset itself

junior pollen
#

so also userWantsToJump = true;

heady iris
#

well, that wouldn't do very much

junior pollen
#

;/

heady iris
#

if (userWantsToJump && isGrounded)

#

what does this line mean?

junior pollen
#

if the user wants to jump and is grounded

#

ah wait

heady iris
#

right

#

so :p

junior pollen
#

!isGrounded

heady iris
#

no, that line is fine

#

but, if it checks that the user wants to jump...

heady iris
junior pollen
#

ah wait no

#

i meant false

heady iris
#

if we're in that if statement, userWantsToJump must have been true

#

ya

junior pollen
#

told you my brain is broken

heady iris
#

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!

junior pollen
#

so isGrounded = false; and userWantToJump = false; in the if statement

heady iris
#

That sounds reasonable.

junior pollen
heady iris
#

Although, isGrounded should get set to false the next time you check for grounding

heady iris
#

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

junior pollen
#

makes sense

junior pollen
heady iris
#

well, you need to figure out when you're on the ground again, right?

junior pollen
#

well doesn't this take care of it? isGrounded = Physics2D.OverlapCircle(GroundCheck.position, 0.15f, groundLayer);

heady iris
#

ya

junior pollen
#

checking for the groundLayer

heady iris
#

so, if you leave the ground, that'll set isGrounded to false

#

once you get out of range of the ground, at least

junior pollen
#

yep

heady iris
#

setting isGrounded later on in FixedUpdate won't really do anything, since the next time FixedUpdate runs, it'll set isGrounded again

junior pollen
#

ohhhh

#

so isGrounded = false; can be removed from the if statement?

heady iris
#

ya

#

note that this isn't vital or anything

junior pollen
#

so it can be either kept or removed?

heady iris
#

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

junior pollen
#

nvm

vernal wharf
#

Hi there, I have a Bootstrap scene as my first scene, and the Game scene as my third scene

lucid crow
#

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 ๐Ÿ˜›

lucid crow
#

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 ?

leaden ice
#

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

lucid crow
#

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

heady iris
#

a state machine isn't anything crazy

rigid island
heady iris
#

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

lucid crow
#

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

sonic zinc
#

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

lucid crow
sonic zinc
#

never heard of a singleton

#

and yea sort of new lol

lucid crow
#
private void Awake()
    {   
        
        //Singleton Pattern
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }

        else
        {
            Destroy(gameObject);
        }
    }
#

this should work ? ๐Ÿ˜›

sonic zinc
#

thanks, I actually just copied that exact code from chatgpt lol

lucid crow
#

haha yea ... thats how i got it ๐Ÿ™‚

sonic zinc
#

it works, I only have 1 character now

#

:D

lucid crow
#

haha beginner helping beginner ๐Ÿ˜› ... cough chatgpt... got us

desert shard
#

DDOL isnt part of the singleton pattern. so you may not need it.

solemn raven
#

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

somber nacelle
faint hornet
#

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

glossy basin
solemn raven
#

quick question , which start function fires first , the parent's or the child's ?

quartz folio
solemn raven
solemn raven
#

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

heady iris
#

does nothing show up in the inspector at all?

#

also, show your code.

solemn raven
#

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;
}

quartz folio
#

what is Element? A plain class?

#

do you have compiler errors in the console?

solemn raven
quartz folio
#

MonoBehaviours do not need to be marked as serializable

#

they will appear in the inspector as object fields

heady iris
#

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

quartz folio
#

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

leaden ice
lament bloom
#

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:

heady iris
#

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

lean sail
#

ignore my statement, carry on

solemn raven
leaden ice
lament bloom
#

holy shit

#

thanks

#

that rocks

ashen yoke
#

then do local rotation

lament bloom
#

switching to pivot instantly solved my problems

#

๐Ÿ‘

glossy basin
#

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

heady iris
# lament bloom ๐Ÿ‘

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?

solemn raven
#

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;
}
lament bloom
heady iris
#

i'm trying to remember where I've seen this error

#

but your code looks valid

solemn raven
#

no , oh could it be an editor bug , interesting.

heady iris
#

it just changes the gizmos

#

I do prefer to leave it on Pivot. I usually put the pivot point in a useful location!

lament bloom
#

hmm, really?

lean sail
lament bloom
#

how do i use the pivot point in changing the rotation

heady iris
#

it does not change anything else

lament bloom
#

iiii seee

#

i understand now ty

#

just needed to use the transform.position as the pivot in the function call

faint hornet
solemn raven
glossy basin
faint hornet
ashen yoke
glossy basin
ashen yoke
#

spatial hash, hierarchical grid @faint hornet

glossy basin
#

this is a technique used in minecraft for example, where the chunks are only loaded according to the player's view distance

faint hornet
faint hornet
ashen yoke
#

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

faint hornet
#

yeah but how do i do that with dynamically generated tiles? they don't move they just are instantiated

ashen yoke
#

whats the difference

glossy basin
ashen yoke
#

do you have any sort of grid in place?

faint hornet
ashen yoke
#

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

faint hornet
#

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

ashen yoke
#

have you read anything i said

faint hornet
#

yes but i don't understand what you mean

ashen yoke
#

then ask a question that would help you understand

#

what exactly you dont understand

faint hornet
#

ok..

glossy basin
#

I get this now, you need to apply the concept as @ashen yoke mentioned, spatial hashing

faint hornet
#

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

ashen yoke
#

that is not related to culling as a concept

#

that is related to unity's specific implementation of 3d culling

faint hornet
#

ahh ok

glossy basin
ashen yoke
#

a DIY culling system wont differentiate between runtime insertions and editor time

faint hornet
#

yeah i don't fully understand how to go about coding my own culling script that is efficient..

ashen yoke
#

ok

#

start in small steps

#

first answer - do you have any grid structure in place?

faint hornet
#

i mean... yeah i guess? every tile holds it's world position data and is stored in a vector2Int dictionary ?

ashen yoke
#

so basic spatial hash

faint hornet
#

not familiar with the term spacial hash but ok!

ashen yoke
#

a dictionary is a hash map essentially

faint hornet
#

so do i need a camera script that handles the rendering of the tiles ?

ashen yoke
#

the key is a hash, an int value

faint hornet
#

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"?

ashen yoke
#

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

faint hornet
#

hmm. ok that makes sence. thanks for clearifying

#

but what do i do from there to create a culling script using the dictionary?

ashen yoke
#

assume instead of V2i dictionary you have a 2d array

#

you need to find all tiles that intersect this line

faint hornet
#
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?

ashen yoke
#

yes

faint hornet
#

so i put cullable tag on the big tiles and the small tiles and it should work?

ashen yoke
#

i dunno i give up

faint hornet
#

lol

#

sorry if i'm really stupid. i'm trying to understand haha

ashen yoke
#

its the same as being given a bag of coins and told to count them and you start counting them one by one

faint hornet
ashen yoke
#

each frame you call the least efficient method in unity to get objects

#

it allocates a new massive array each frame

faint hornet
#

yeah that is not very optimized

ashen yoke
#

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

faint hornet
#

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

ashen yoke
#

yes

#

thats the whole thing im trying to explain from the start

faint hornet
#

ahhh i see. ok contiue explaining lol

ashen yoke
#

what is this

#

the whole concept is to narrow down the search for potential collision candidates

faint hornet
#

right. i understand that. but i'm just not understanding how you want me to actually narrow it down?

ashen yoke
#

now we have a 2d array in place, each index in that array is a list

glossy basin
#

@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

faint hornet
#

like i get that you want me to find the stuff nearest to the camera to simplify by alot but how?

ashen yoke
#

each "cell" of this array contains tiles inside of the cells

#

so in the line example, we

  1. find out which cells the line intersects
  2. get all the tiles in those 2 cells and test them for collision
#

this narrows down the search from 1000s of objects to 200

faint hornet
#

yeah so i have two dictioanrys . one that holds all the large tiles. (parents) and one that holds all possible smaller tile (child)

ashen yoke
#

that is not enough

#

a barebones dictionary doesnt optimize anything by itself

#

you need a grid

faint hornet
ashen yoke
#

there are algorithms online for line grid intersections but yes that is raycast in essense

faint hornet
#

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)

ashen yoke
#

forget about the raycast

faint hornet
#

ok

ashen yoke
#

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

faint hornet
#

it intersects two parents tiles

ashen yoke
#

lets call them buckets

#

or cells

#

because tiles are the objects you want to find

faint hornet
#

buckets. ok

ashen yoke
#

and buckets are what store them

faint hornet
#

i have a script that holds these "buckets" i call them chunks

ashen yoke
#

now instead of Dictionary of your tiles, you will have a dictionary of buckets

#

each bucket can be simply a list

faint hornet
#

i do have a dictioanry of these buckets.. i have a chunk dictionary

ashen yoke
#

then you have the problem already solved

#

all you need is to intersect the camera frustum with the buckets

faint hornet
#

ok so if the bucket is intersected. then i enable all children in the bucket?

ashen yoke
#

yes

#

6 buckets here

faint hornet
#

yes

#

is the blue square a frustrum?

ashen yoke
#

yep

faint hornet
#

ok so i want to probably put a frustrum just outside of the cameras view..

ashen yoke
#

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

faint hornet
#

is the frustrum a volumetric thing or just a perimeter thing

ashen yoke
#

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

faint hornet
#

but wait.. question

ashen yoke
faint hornet
#

i currently have the code remove the collisions on the bucket once they are purchesed.. is this an issue?

ashen yoke
#

no

faint hornet
#

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

faint hornet
ashen yoke
#

those are 2 different examples

#

one was with imaginary line, one with imaginary camera

faint hornet
#

i know... but what i'm asking is if it is volumetric

ashen yoke
#

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

faint hornet
#

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"

ashen yoke
#

no frustum is a geometric shape

#

this is a frustum

faint hornet
#

ok so it is area.. not an outline

ashen yoke
#

cameras render the world

#

with the help of the camera frustum

faint hornet
#

ok so ya all the yellow area is part of the "intersection" right?

ashen yoke
#

nope thats just the bottom of the frustum

faint hornet
#

ok so everything inside the Volume of the shape is in the "intersection" >

#

?

ashen yoke
#

better call it overlap

faint hornet
#

ok sure. but thats what i meant by volumetric

ashen yoke
#

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

faint hornet
#

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

ashen yoke
#

tho thats normalized

#

there is no depth, the layers are simply a render order customization

faint hornet
#

ok

ashen yoke
#

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

faint hornet
#

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);
    }
}
ashen yoke
#

camera.bounds to Rect will suffice

faint hornet
#

this is still inefficient becasue it's still checkign every object in scene right?

ashen yoke
#

yes

#
Rect GetCameraRect(Camera camera)
{
    camera.bounds ... 
    return rect;
}
faint hornet
#

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;
            }
        }
    }
}
ashen yoke
#

is this ai generated?

faint hornet
#

yes lol

ashen yoke
#

im done

faint hornet
#

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

faint hornet
# ashen yoke is this ai generated?

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

wide fiber
#
  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? ๐Ÿ˜ฆ
cosmic rain
leaden ice
#

What is controller.RotChanged and how does it work?

wide fiber
wide fiber
#

it is for my new input system

leaden ice
#

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 performed in the callback
#

Currently you have the equivalent of Input.GetKey when what you want is Input.GetKeyDown, make sense?

wide fiber
wide fiber
#

hahaha

leaden ice
#

It's... definitely more complex. Once you get the hang of it it's much more powerful though

latent latch
#
//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.

faint hornet
#

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?

shell scarab
faint hornet
#

it seams to be awake functions and start methods

glossy basin
glossy basin
glossy basin
#

expand player update canvas

#

is it still start and awake

#

?

faint hornet
glossy basin
#

Ahh, thats just Unity UI, nothing wrong with your code

faint hornet
shell scarab
#

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

faint hornet
#

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

glossy basin
glossy cloud
#

can anyone please help me, im really struggling

glossy basin
#

I have no idea if Unity UI toolkit really performs better than unity canvas

glossy cloud
#

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

glossy basin
faint hornet
glossy basin
#

in the profiler, whenever your game lags, it makes an spike in the profiler which you can inspect

glossy basin
faint hornet
shell scarab
faint hornet
#

i have one canvas and it basicly does nothing

glossy basin
shell scarab
#

well what's nothing?

glossy basin
#

also as i mentioned, there must be something else going on

shell scarab
#

well clearly there's something going on with the canvas

glossy basin
#

I suggest you enable garbage collector checkbox

faint hornet
#

i'll turn it off completly. and see what happens

glossy basin
shell scarab
# glossy basin

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.

glossy basin
#

just curious, since your project loads a massive amount of tiles, how much time does it take to generate all those tiles?

faint hornet
glossy basin
faint hornet
#

i don't like hearing those words lol

glossy basin
#

but also, I noticed you have 3K batches, that's way too high

glossy basin
faint hornet
#

yeah i do. thats correct. the batches are high

#

how do i reduce that? with culling right?

glossy basin
warm oasis
#

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

faint hornet
#

ok so i have a culling script on my main camera that doesnt seem to be making a difference in it.

warm oasis
#

from your screen most of this time is rendering so...

faint hornet
warm oasis
#

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?

faint hornet
#

i do have a frustrum culling. its just not working ro something.. i dont understand it

plucky karma
warm oasis
#

if it's not working it doesn't mean it's not the solution.
but share code somewhere correctly, and following rules

glossy basin
faint hornet
glossy basin
#

share your culling code, maybe someone can tell you the right way

faint hornet
#
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

glossy basin
#

also if your objects have a material, make sure to enable gpu instancing on them

faint hornet
#

but this code is't throwing any errors

faint hornet
warm oasis
#

you click on those objects shaders and scrolling down and check gpu instancing

warm oasis
#

he said only if

#

so that's not the issue

cosmic rain
#

Wdym "if"? Without a material it wouldn't be rendered.๐Ÿ˜…

warm oasis
#

but your code has so many issues i can't guess and no one can so

glossy basin
warm oasis
#

but anyway that's not even the issue at all

faint hornet
warm oasis
#

why the fuck are you talking about material issues when talking about frustrum culling

#

you goddamn madlads

faint hornet
#

because im a fucking idiot trying to figure shit out

warm oasis
#

that's your issue

glossy basin
warm oasis
#

but everyone's trying to tell shit, they do.
but read further

faint hornet
#

yeah and im asking for help. if you don't want to help, thats cool.

warm oasis
#

he says it doesn't even work

glossy basin
warm oasis
#

unless he has 520 custom shaders

#

that's not a thing

#

well you get me

faint hornet
cosmic rain
#

Unity has frustum culling by default, so I don't see the point of what you're doing @faint hornet

faint hornet
glossy basin
cosmic rain
warm oasis
#

now that's helping

cosmic rain
#

*would involve overhead in addition to unity frustum culling.

warm oasis
#

gpu instancing is bs unless they all do the same movement at the same time or behave the same anyway

cosmic rain
#

@faint hornet what are you trying to do?

warm oasis
#

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

faint hornet
warm oasis
#

if it's tiles tho i'd run chunkes

cosmic rain
faint hornet
#

i have chunks

warm oasis
#

so your clients doesn't run them all at the same times

#

you do? i see

faint hornet
glossy basin
cosmic rain
warm oasis
#

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

faint hornet
#

here is my new stats after changing materials to gpu instancing..

cosmic rain
#

3k batches is a lot...

faint hornet
#

HOW DO I REDUCE IT

#

tis the question

warm oasis
#

the way to optimize rendering is only three way sided,
batching,
culling,
render calls?

cosmic rain
warm oasis
#

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

glossy basin
#

@faint hornet how many child items do your chunks have

warm oasis
#

so many things for so many projects we can't guess

glossy basin
#

can you select a chunk and show us the outline like this

warm oasis
#

64 children objects drawing all faces?

faint hornet
warm oasis
#

or only foreseeable faces

faint hornet
#

so looks like this... let me get a picture

cosmic rain
#

What's all the "purchase" and "xxxx amount" meshes?

faint hornet
glossy basin
faint hornet
warm oasis
#

this pic doesn't show us anything apart from bad eyepics

cosmic rain
faint hornet
warm oasis
cosmic rain
#

And your hierarchy is almost empty...

warm oasis
#

but i don't see those issues apart from voxel so

#

i assumed lmao

glossy basin
warm oasis
#

terraria 2023

cosmic rain
#

Oh it's a tile prefab

glossy basin
#

I noticed the problem

#

I think

faint hornet
#

im listening lol

glossy basin
#

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

warm oasis
#

wait

#

that's all ui?

glossy basin
faint hornet
#

ok ill try that

warm oasis
#

why

faint hornet
#

no its not UI

warm oasis
#

i mean rect is UI part

glossy basin
faint hornet
#

ok let me try changing that'

glossy basin
#

he should have a Transform instead of a rect, that can be fixed by using a sprite component

faint hornet
#

should i make all the siblings transform and leave the parent a rect?

glossy basin
#

Sprite render *

warm oasis
glossy basin
warm oasis
#

how do you create those tiles?

#

since that's what you're showing no?

faint hornet
#

im using grid layout groups.. is that an issue too?

warm oasis
#

yes

#

it's ui objects

glossy basin
warm oasis
#

unless you swap

#

tho i can't quite say if it's optimised

faint hornet
#

i like the rect transform better

warm oasis
#

as i never worked on it

#

rect transform is user interface only

glossy basin
warm oasis
#

and would never be useful in gameplay feature

glossy basin
#

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

glossy basin
glossy basin
cosmic rain
#

Yes, grid is used for tilemaps usually.

#

At this point I don't understand why unity tilemaps are not being used..?

warm oasis
#

you could retrieve grid or cells from tilemaps easily from them

#

they have api

faint hornet
#

i like it more becasue it's easier to use

warm oasis
#

but it's not made for it at all it's your issue there

#

to the point no one guessed it

#

trust me

faint hornet
#

when i take all those rects off it makes all the instatiations spawn in the same spot instead of on the grid

warm oasis
#

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

glossy basin
cosmic rain
faint hornet
#

lol

warm oasis
#

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

cosmic rain
#

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.

warm oasis
#

UI is for UI, as much as you wouldn't use coroutine for gameplay features

faint hornet
#

what if my game is kind of like a ui based game? all teh tiles will be clicked at some point

warm oasis
#

tiles are tiles

#

for unity

#

it doesn't care about how you would think about it

warm oasis
#

because that's how anyone would think about it

#

you would pinpoint where your click with it's api

faint hornet
#

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

warm oasis
#

and where it is with your click

chilly prawn
#

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.

faint hornet
#

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.

warm oasis
faint hornet
warm oasis
#

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?

faint hornet
#

@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?

warm oasis
#

you can do this on a tilemap really fine

glossy basin
warm oasis
#

there's lots of tutorials "tilemap" wise or sprites, or even 3d

faint hornet
warm oasis
#

tilemap is kind of more recent so i agree there's less examples

#

but it's still possible logic wise

glossy basin
#

Everything in Unity that can be clicked in inspector is basically a GameObject

warm oasis
#

even though in term of tech it's quite old

glossy basin
#

this part is the GameObject

warm oasis
#

we would all be quite happy to help you realise it

cosmic rain
faint hornet
warm oasis
#

make a struct of it then

faint hornet
#

i feeel like i need to take a college course on this. there are just too many posibilites as a beginner

dry lantern
#

does anyone know how to fix this? (it happened when i downloaded post processing)

warm oasis
#

study every c# course, then game design pattern, and go forth

#

but you're welcomed to ask anytime ๐Ÿ™‚

faint hornet
#

awesome thank you

warm oasis
#

just, remember any framework, game engine, you can't go against it