#archived-code-general

1 messages · Page 315 of 1

river junco
#

yeah bruh

sacred bane
#

Same

river junco
#

sahi hai bhai

sacred bane
#

What age r u? If i may ask

river junco
#

24

sacred bane
#

Cool

#

Im 16

#

Im from the south tho

river junco
#

okok

#

i'll be happy to help you out, anyways

#

gg

sacred bane
#

Yeah thanks 🙂

#

Being indian myself, Its always the indian guy who helps me lmao

#

When it comes to studies, gamedev haha

signal ridge
#

Anyone succesfully using a one source of truth type state management system ? Redux.NET seems pretty good but im not sure about unity compatibility. I wish Pinia could be ported to C#.

chilly surge
#

I've written my own reactivity system inspired by Vue's and used it in my Unity project. A primitive reactivity system is pretty simple to write, especially if you are willing to make some tradeoffs like not doing automatic dependency tracking, that basically reduces the whole thing to less than 100 LoC.

signal ridge
chilly surge
signal ridge
novel bough
#

@swift falcon https://www.youtube.com/@Brackeys watch this guy

thin aurora
uneven monolith
#

Hey! I have
-float angle in degrees(can be easily changed to radiants)
-origin vector2 point(game is 2d)
-float distance /magnitude
And i want to generate Vector2 with that angle and distance from origin,

I know how to do this in math like with explinations and calculations, but not sure how to approach it in unity components lol

#

like ofc i can do the long way but Vector2. has so many methods and stuff so i think there should be some easy way

#

nvm found it online lol

keen lantern
#

Is there an easy way of checking if the transforms parent has a parent with a certain tag?

#

The whole parent of parent and child of child stuff is a little confusing to me

dusky lake
latent latch
keen lantern
#

Do I just add an extra transform.parent for every parent that I want to go up?

latent latch
#

probably, but not a way I'd code it all. I'd make a specific field for that reference and make sense of what this greater parent is

keen lantern
#

Oh interesting, I would assume that I can do the same with transform.child?

latent latch
#

sure, but if you can do it at editor time, just bind those references on the editor too

dusky lake
leaden yoke
#

I have added a run animation to my character but when I'm not running the running animation is still happening. how do I make it so when I'm running (pressing LShift & W) the run animation plays and when I stop running the animation also stops.

slim gate
dusky lake
keen lantern
leaden yoke
keen lantern
#

Im gonna have to write this down 👀

dusky lake
leaden yoke
# dusky lake Do you have an animation graph?

im still new to this all I did was follow a youtube tutorial which is this: https://www.youtube.com/watch?v=9H0aJhKSlEQ&ab_channel=syntystudios

Animate a character with Mixamo
Check #SyntyStudios for more videos
Subscribe to Synty Studios on YouTube - http://bit.ly/2YPlWRp
Like Synty Studios on Facebook - https://www.facebook.com/syntystudios/
Check out all the different content available on the Synty Store - https://syntystore.com

Files required: https://www.dropbox.com/s/lyc53bvsohi...

▶ Play video
dusky lake
#

Whenever you are running you set the "running" bool on the animator to true and it transitions to the running animation, when you stop, set it to false and it transitions back to idle

rugged storm
#

when i run EvaluateTurns turns.IndexOf(turnGrahic.turn)Returns -1 why is this (MakeNewturn gets called about 6 times and then EvaluateTurns right after so nothing else should be messing with this)

dusky lake
tawny elkBOT
rugged storm
unreal valley
#

What is best practice for using Floats?

slim gate
thick terrace
dusky lake
unreal valley
# slim gate what

If I can represent a float as an Int what's the point of using a float. Essentially is what Im asking.

slim gate
#

you cant, not in most cases. Not sure if I understand

rugged storm
unreal valley
#

Ex. 15%, instead of 0.15f I just do int 15.

dusky lake
rugged storm
#

OH

dusk apex
slim gate
rugged storm
#

than you i can believe i over looked that

slim gate
#

how do you represent 1.5f as an int

heady iris
#

you can find an integer that looks kind of like any given float

slim gate
#

lol

dusk apex
#

If anything, use approximations and ranges when comparing values

heady iris
#

that's not meaningful, though

#

123 kind of looks like 1.23f, but so does the string "1.23"

#

use floats when you need to represent a non-integral value

unreal valley
dusk apex
thick terrace
#

floats are inherently a little bit inaccurate, if you need exact precision you can use int types but for most physics and game logic it doesn't matter

unreal valley
#

I really just wanted to know if I should continue using floats or swap to int's. And in the future if I run into code that I think needs to be a decimal, should I convert to int to avoid these problems.

thick terrace
#

never expect exact equality when comparing the results of float operations, use Mathf.Approximately or whatever

slim gate
#

well if you need floats you use floats and if you dont you use int

unreal valley
#

To go into more detail. It was an accuracy up being applied to a character. Then it got hit with accuracy down. It SHOULD HAVE been 0.

slim gate
#

no reason to use a float if int can do the job

unreal valley
thick terrace
#

things like RPG stats are often better as ints, like currency, you actually do want the exact precision

azure heath
#

Hi, I have an event to which I subscribe 2 methods (line 15 of ChillState and line 39 of InputManager), but one method (the one in ChillState) isn't being called when the event is invoked. I used Delegate.GetInvocationList to check that it's actually subscribed and it is. Any thoughts why this might be?
https://hastebin.com/share/gayudirose.csharp
https://hastebin.com/share/gimemihoju.csharp

unreal valley
#

I also used to have Unit Level up bonus's which were in the same boat, it was a aList<StatType,float> . Ex. Strength 2.6 * base each level up. But that can easily be remedied with Mathf.RoundToInt

#

@thick terrace Thanks for the talk.

indigo verge
#

Any response for this earlier question?

leaden ice
azure heath
# leaden ice I don't see where you invoke the event

Cast is subscribed to OnStartTouch (InputManager Line 103), which is invoked in TouchPressed() (Line 121), which is subscribed to touchPressAction.started (Line 36), which is invoked when you tap the screen

#

it's a bit convoluted ik

leaden ice
#

If you do that it's not going to pick up updates to Cast

#

Cast gets reassigned when you subscribe something new to it

azure heath
#

Oh right yeah I remember now I had the same problem a while ago. That's why I made that AddToUncast() Method on line 139

#

Oh wait that's not quite the same

#

But thanks I see your point

graceful latch
#

Hey, i was wondering if it is possible to make a variable in an interface optional. i would like the string to be optional

#

because at the moment i get this error "Assets\Dev\InteractableObject.cs(2,50): error CS0535: 'InteractableObject' does not implement interface member 'IInteractable.Tooltip'"

rigid island
#

also thats a property , interfaces cannot have member variables

leaden ice
graceful latch
late lion
surreal cloak
#

is there a way to check if a collider has collided with any raycast without using hitInfo.

warm canopy
#

are you using ECS or gameobjects?

rigid island
#

also colliders dont hit rays, raycast hits colliders 😛

surreal cloak
surreal cloak
rigid island
#

maybe explain what you're doing , might be able to offer better alternative

warm canopy
#

ECS or gameobjects, @surreal cloak ?

#

that's gameobjects, btw.

leaden ice
rigid island
warm canopy
#

without using HitInfo I'm assuming is raycasthit, I dunno. just wanted to feed info.

rigid island
#

I mean you could just, not use the parameter in Raycast though?
It would be useful if they explained their usecase lol

leaden ice
#

RaycastAll gives RaycastHits too though

rigid island
#

ya lol also this

warm canopy
#

correct

#

all the casts do so.

rigid island
#

guess we'll never know what

for something i am doing
means :p

warm canopy
#

the CheckBox, CheckSpehere, etc returns just a bool. the *casts methods use raycasthit, and has certain flexibility.

leaden ice
#

Those are just shortcuts for Overlap methods which are not casts

lilac vortex
#

what other ways can I save data?

solid slate
#

https://hastebin.com/share/kunebukeku.csharp hi, i am making a script for the player to throw a katana but I have a coroutine that returns the sword to the player that for some reason runs after the sword returns for a little bit (sometimes). this makes it (I think) so after a few consecutive throws, the katana will throw for like half a second and immediately return, not going its full length. (btw this happens when the player hits the enemy not just throwing it into the open sky.) tried making it so when you catch the katana and even when it is in the distance to catch to stop both theThing and the FollowHand coroutine but the issue persists

knotty sun
pliant oriole
#

Say I want to serialize a class I have no control over, like something from a Unity package

#

Is there a way to do it, or is it just not possible?

latent latch
latent latch
#
IEnumerator SpinSwordAsThrown()
{
    while (!returningSword)
    {
        transform.Rotate(thrownSpinSpeed, 0, 0);
        yield return null;
    }
}

What you're doing here is a good example

solid slate
#

ah

latent latch
#

FollowHand() calls StopCoroutine on itself which I'm not sure how that behaves

solid slate
#

i see

#

alr ill try that

latent latch
# solid slate i see

Your variables inside of that coroutine too may not being reset as they are member variables, so make sure stuff like the returning force is changed back to defaults when making a new coroutine.

latent latch
#

Ah, I see. My best two guesses would be the values arent resetting, or that you have multiple coroutines running that are changing the values which you may not be aware of.

solid slate
#

yeah that makes sense

latent latch
#

which is why vs debugger is great for debugging coroutines

solid slate
#

how do i debug coroutines tho theres no way to get its status other than bools which isn't really helpoing in my case

latent latch
#

If you're doing it by logs then putting them directly in the coroutine yourself

#

unfortunately not easy to debug per instance though (well, you can identify them inside the coroutine scope, but iterating over a list of coroutines does not yield anything too useful)

solid slate
#

oh

solid slate
rocky basalt
#

Could anyone tell me the most straightfoward way to ensure text (tmp) only shows from one direction, like a real life notecard, even if the material is transparent?

rigid island
rocky basalt
knotty sun
#

I gues this is 3D TMP so parent it to a Quad

rigid island
#

ohhh the 3D one

rocky basalt
#

I may be misunderstanding, but parenting it with a quad didn't fix it

#

and yeah it's 3d

knotty sun
#

i did. Did you flip the Quad 180?

rigid island
#

just seen that lol

#

huh , didnt know it was a fix

rocky basalt
rigid island
#

huh it works

#

nvm didn't work for me

rigid island
rocky basalt
#

It's a VR app where user can grab and manipulate the notecards, so it's a little unorthodox I guess. I'm surprised it isn't more straightforward to solve this lol

rigid island
#

but yeah thought there would be an option on the 3D mesh extra settings to render one sided but alas none I found

rocky basalt
#

I'm actually using the asset Nova for my UI, if you're familiar with it. It's all world space

#

It integrates TextMeshPro

#

Unity's UI just looks like puke to me so I preferred to use Nova. Alas it leads to situations like this tho, hah

rigid island
#

Oh I'm not familiar with it, are you able to use the TextMeshPro UI version of text? I would use that then

rocky basalt
#

Even with that it doesn't seem to make a difference.

#

Oh well, it's not a total gamebreaker for me, but I'm sure I'll run into this issue again someday

rocky basalt
#

are you using sorting layers or anything

knotty sun
#

nope, just put 0.1 on the z of of the text

rocky basalt
#

yeah the problem is the notecard is a semi-transparent 3d object that needs to be consisent on both sides, i just want the backside to not show the text. might require a specific shader or sth

#

Ohh I see, if the quad is like 'inside' the 3d object it will still work I guess

indigo verge
#

What is a good way to have a list of classes that derive from a base class, but which hold unique data types, and then retrieve them?

Like, say, PositionData derives from BaseData, and AnimationData also derives from it.

PositionData holds a Transform, and AnimationData holds an AnimationClip.

I then want a list of BaseData, which contains instances of both PositionData and AnimationData.

Then I have a Function, "PlayAnimation", which takes in a BaseData as a parameter, but I want it to only ATTEMPT to retrieve an AnimationClip from it, so if it's passed an invalid BaseData which doesn't contain that variable, it doesn't throw an error.

Does any of this make sense? Apologies if I'm not explaining it well.

thick terrace
indigo verge
#

I'm working on a modular statemachine for a turn-based RPG, so I need to be able to build complex custom "actions" that the player can perform.

thick terrace
#

at what point would you pass a non-AnimationData object to PlayAnimation though? i'm wondering why you'd need to avoid something like if (data is AnimationData animationData) PlayAnimation(animationData)

steady moat
indigo verge
#

Look, this should explain it better. Here's a snippet of my design document, where I'm trying to piece together the architecture of a state machine for playing character actions.

winged shadow
#

has anyone used urp render objects and stencil shaders

i need helpp

indigo verge
#

Basically, I want an action to be able to;

Bring up a UI unique to it when selected
Perform a unique action with that UI input
Perform multiple actions if need be, in any order
Provide Control, Modularity, and Complexity for designing actions, playing them out, and modifying them in editor or runtime.

#

So I'm designing it to be polymorphic, and am working on what sort of design elements suit that.

steady moat
thick terrace
indigo verge
steady moat
indigo verge
#

Ect, ect

solid slate
#

https://hastebin.com/share/ilepizawuc.csharp how come when the katana hits an enemy it comes back fine but if it doesnt hit an enemy it just flies off into the distance

steady moat
steady moat
steady moat
indigo verge
#

I've read that using coroutines for Turn Based Combat is common, though?

leaden ice
#

Coroutines sound like a nightmare for turn based combat. Coroutines are really just lightweight/poor man's state machines. A full fledged state machine would be better

steady moat
#

No, it is not. It is possible to use them, but definitely a bad idea. You have less control over them. You should favor using your own Update logic.

latent latch
#
public abstract class EntityConditionsBool : ScriptableObject
{
    public abstract bool EvaluateCondition(IEntity target);
}

public class UnderActiveEffect : EntityConditionsBool
{
    [field: SerializeField] private ActiveEffectSO ActiveEffectSO;

    public override bool EvaluateCondition(IEntity target)
    {
        foreach (ActiveEffectBundle activeEffectBundle in target.ActiveEffectBundles)
        {
            if (activeEffectBundle.ActiveEffectSO == ActiveEffectSO)
            {
                return true;
            }
        }

        return false;
    }
}

So I was thinking of a class like this for conditions for characters. Problem is I'm not too sure of the best way to structure it for return types, as well as being able to work with it on the editor.

#

I dislike the SO Idea as that's a lot of asset bloat so I'mma just use serialize references

#

Another class would be something like this

public abstract class EntityConditionsInt : ScriptableObject
{
    public abstract int EvaluateCondition(IEntity target);
}

public class GetNumActiveEffectStacks : EntityConditionsInt
{
    [field: SerializeField] private ActiveEffectSO ActiveEffectSO;

    public override int EvaluateCondition(IEntity target)
    {
        foreach (ActiveEffectBundle activeEffectBundle in target.ActiveEffectBundles)
        {
            if (activeEffectBundle.ActiveEffectSO == ActiveEffectSO)
            {
                return activeEffectBundle.ActiveEffectApplications.Count;
            }
        }

        return 0;
    }
}```
#

So it's like a class for each type of return value that I want? Ye or nah? I feel like the serialization is what's holding me back here

steady moat
# latent latch I dislike the SO Idea as that's a lot of asset bloat so I'mma just use serialize...

I usually implement "Serialize Condition" as "SerializeReference". Not sure what you are referencing for your issues ?

It seem to me that you are trying to serialized to much "code" and instead you should simply code it. Do not overthinking it, just make a class for every scenario. If you really, really wants to do that, you should instead create a Graph Editor such as what you can see with VisualScripting. It is 100% better to edit "serialize code" in this format.

latent latch
#

Coding it directly would be a solution, but I was looking for like absolute modular code that I could just wrap these in with other classes

#

Probably a bunch of other classes where I do need to know if they have a specific amount of effect stacks, if they are under % hp, stuff like that

steady moat
latent latch
#

Yeah, I can see that and it would probably just be easier to duplicate code if I need to

#

It is nice though a lot of my systems I can just move and replace without touching the underlying code because how component heavy it is

steady moat
#

Obviously, it depends on how much you are going to use those condition and how specific they are.

fervent coyote
#

Hi there, simple question, how can I get an angle of a direction vector:
_newDir = Handler_Gamehandler.Astro_UnitCircleVector3(transform.eulerAngles.y + (i * 45));
Instead of transform.eulerAngles.y I want to use something like PathfindingDirection.y but it is obviously, 0
Could I have some pointers for this problem?

latent latch
#

Visual scripting does seem like a fine idea too, but it's one of those tools where I'd forget I was even making a game

steady moat
#

If you make a FireBall, just code a FireBall class.

#

No need to make everything abstract and generic.

latent latch
#

but generic projectile that has a chance to explode into smaller fireballs that have a chance to burn the enemy and make the enemy explode when they die is pretty cool too

#

swap out the fireballs for icebolts in a single SO ;)

steady moat
#

It works well if your game is not that complicated. But when you start to have specific condition that only make sense in a specific context it start to being a hindrance more.

latent latch
#

It's unfortunate, but larger reason it is this modular is because I'm bad at having stuff planned out in design

steady moat
latent latch
#

one day I want fireball, the next day I want fireball storm

steady moat
#

Modular means that you are adding limitation and you make a lot of assumption.

#

From the little experience I have, I can guarantee you that the worst you are at planning the worst modular architecture are. It is always 100% easier to replace code of a single whole class then replace code of 5 smaller class and adding context specific module.

pulsar holly
#

How can I make an if statement using colors and/or arrays?

rigid island
fervent coyote
#

Yeah, just check the color and make sure it's equal

pulsar holly
rigid island
#

==

pulsar holly
fervent coyote
#

if (colors[i] == color) for Arrays

rigid island
#

that OnTriggerEnter2D 😵‍💫

pulsar holly
#

What's [i]?

fervent coyote
#

Assuming you use a basic for loop... for (int i = 0; i < 10; i++)

pulsar holly
#

That's the new code.

#

Well at least the code I used

rigid island
#

time to do basic c# again 🙂

#

that's def not the equality operator

fervent coyote
rigid island
#

a vector is a direction pretty much no ?

fervent coyote
#

Yeah, but I'd like to add unto it:

{
    _newDir = Handler_Gamehandler.Astro_UnitCircleVector3(angle + ((i * dirA) * 45));
    //If not detecting a wall, go ahead
    if (!Physics.Raycast(transform.position, _newDir, distWall)) 
    {
        break;
    }
}```
Here is the full context: I'm trying to test directions to see if a certain direction is open for the npc to move towards too
indigo verge
rigid island
fervent coyote
#

Not using navmesh

#

Trying to implement my own custom one

rigid island
#

ahh ok yeah trig math is not my forte

#

also might want to post Astro_UnitCircleVector3 for anyone who might know

fervent coyote
#
{
    float unitCir = degree * Mathf.Deg2Rad;
    return new Vector3(Mathf.Cos(unitCir) * radius, 0, Mathf.Sin(unitCir) * radius);
}```
simple egret
#

I'd do it with a Quaternion that describes one "direction increment" (360° / number of directions to check)
Then multiply it with your direction vector to rotate said direction vector

#
Quaternion rot = Quaternion.Euler(0, 360 / 6, 0);
Vector3 dir = transform.forward;

for (int i = 0; i < 7; i++)
{
    dir *= rot;
    // use 'dir' for raycast
}
#

Something roughly like this

fervent coyote
#

Oh, I really don't want to use transform.forward

simple egret
#

The direction is any direction vector you want

#

As long as it's normalized

fervent coyote
#

Oh yeah it is

solar wigeon
#

helo, i hav been making a 2d game i wanted to ask if i could make a infinite random generation but i want to keep some stuff the same like the sky and the ground and iwant it so after the player leaves a part it disapears behiund him any tutorials u guys can recommend i cant find any

solar wigeon
#

yep

rigid island
#

lookup endless runner 2D , many tuts on it

#

generally involves keeping track of position and if it goes above threshold spawn pieces

indigo verge
steady moat
indigo verge
#

In theory, I could have a single CombatState which just assigns a player a full list of their States to travel through and all information needed for all of them.

faint hornet
#

hey everyone, looking for a solution to finding the 4 corners of the screen on a world space canvas.
my world space canvas is much larger than what the camera can see but i want to find those corner coordinates of the screen corners on the canvas.

any tips?

fervent coyote
simple egret
#

That would be 360 / 8 or just putting 45. Afterwards it depends on the initial direction vector and around which axis you need to rotate it

#

My example assumes a direction that is flat (no Y value) that needs to be rotated around Y

#

(it would make a circle when viewed from the top)

#

Use the stuff in the Debug class to visualize the resulting direction vectors

swift falcon
#

what's a good way to go about a database for data needed in game, say a list of weapons with their stats?
i've tried the scriptable object route and it works but is super annoying when you want to edit a lot of them at the same time
i feel like something with a table format would be easier, say CSV, would that be a decent idea?

fervent coyote
#

Gives me:

#

I just need it around a circle which is why I requested the angle in the first place

simple egret
#

What's dirA and why is it included in the rotation quaternion?

fervent coyote
#

It's a simple -1 or 1

simple egret
#

Also not sure why you made _newDir a Quaternion, it's supposed to be a Vector3 for it to work properly

fervent coyote
simple egret
#

Right, the operator only works on one side because of matrix multiplication rules

#

_newDir = quat * _newDir;

fervent coyote
#

Let me try this

#

Alright, that does work

#

But I'd like to it to be rounded to the next 45*, the initial rotation

#

I think I got somethign but I'm not sure

indigo verge
# steady moat new Action(MyParameters)
public abstract class CombatState
{
    protected ActionStateData stateData;

    // Constructor to initialize CombatState with ActionStateData
    public CombatState(ActionStateData data)
    {
        stateData = data;
    }

    // Virtual method to be overridden by derived classes
    public abstract void Evoke(ActionStateManager actionStateManager);
}

So basically something like this, as a constructor, so when I have a CombatState, it requires the correct information by default?

fervent coyote
#

The reason I want to round it the nearest 45* is so I can avoid things like this happening:

#

Okay, I think I'm confusing you guys, sorry, I mean I want to snap it to the nearest 45* angle

rocky basalt
#

There's no way to successfully do a 'GetComponent' on a component you've disabled previously, right?

somber nacelle
#

have you tried it?

rocky basalt
#

yeah, it returns null. and google indicates it's not possible. wondering if there's some other workaround without having to keep references

somber nacelle
#

getcomponent should still return a disabled component. are you sure you are calling it on the right object and that the component is disabled and not destroyed?

rocky basalt
#

ok my bad, i read some google results wrong and it confused me. sorry

somber nacelle
#

you said you tried it

simple egret
#

Wording is ambiguous, we don't know if you're attempting a disabledComponent.GetComponent<T>() or a GetComponent<SomeDisabledComponentType>()

#

But shouldn't matter, both work

rocky basalt
#

yeah it was returning null because i did something else wrong. i misread some google search results and thought the issue was getcomponent doesn't work on inactive components

simple egret
#

GetComponent will find and return inactive components, and you can call GetComponent on a disabled component.
Disabling only prevents some Unity messages like Update and FixedUpdate from running, the other members are still fully accessible

keen lantern
#

Does unity have anything that lets me easily change a gameobjects layer through script?

#

ah nvm, seems like it is something as simple as adding a .layer at the end

fallow light
#

which would be the reason for a function (in this case Die) to not be called unless the highlighted variable is set to public? Even though Im not trying to access it from any other script...

#

I noticed, however, a weird behaviour in Unity while working with this: When the variable health is public and I run the game, the function Die is still not called when the condition for it is met. When I quit and run the game a 2nd time, the function is called immediately without the condition being met...

leaden ice
fallow light
leaden ice
#

Why not show all the relevant code

#

!code

tawny elkBOT
fallow light
#

and this is from other script

leaden ice
#

That makes little sense

#

just do it in TakeDamage

#

Anyway - Debug.Log is your friend

#

log what the health is

#

I would guess it's not less than or equal to 0

fallow light
#

health's value actually decreases, but for some reason there's no effect

leaden ice
#

show the code

#

and show what logs

spring creek
leaden ice
spring creek
#

Could you be looking at the wrong one?

leaden ice
#

I would guess that your code is probably referencing a prefab

#

the enemyAI reference

fallow light
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicEnemyAI : MonoBehaviour
{
    int health = 100;
    EnemyCounterScript counter;

    // Start is called before the first frame update
    void Start()
    {
        counter = FindObjectOfType<EnemyCounterScript>();
    }

    // Update is called once per frame
    void Update()
    {
        if(health <= 0)
        {
            Die();
        }
    }

    void Die()
    {
        counter.enemies--;
        Destroy(gameObject);
        Debug.Log("Die is working");
    }

    public void TakeDamage(int dmg)
    {
        health -= dmg;
        Debug.Log(health);
    }
}
#

That's the enemyAI code

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawnerControl : MonoBehaviour
{
    [SerializeField] GameObject spawner;
    [SerializeField] GameObject enemyPrefab;

    [SerializeField] BasicEnemyAI enemyAI;

    // Start is called before the first frame update
    void Start()
    {
        Spawn();
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown("p"))
        {
            KillEnemies();
        }
    }

    void Spawn()
    {
        Instantiate(enemyPrefab, spawner.transform.position, Quaternion.identity);
    }

    void KillEnemies()
    {
        enemyAI.TakeDamage(100);
    }
}

leaden ice
#
    void Update()
    {
        Debug.Log($"My Health is {health}");
        if(health <= 0)
        {
            Die();
        }
    }```
#

Do this

leaden ice
#

given that the enemy seems to be getting spawned in Start

#

and you're ignoring the return value of Instantiate

#

the only possible conclusion is that you have referenced a prefab in the inspector

#

obviously you are then just doing damage to the prefab

#

not to the actual enemy in the scene

#

The reason this might start to "work" when you make it public is that you are then serializing the health variable

#

and so it's saving between play sessions in the editor

#

You need to actually reference the copy of the enemy that you spawn

#

Instantiate returns that reference for you.

fallow light
#

I see

fallow light
#

thanks btw

leaden ice
fallow light
#

actually, I have a huge mess in these codes... looks like I will have to fix a lot of mess

keen lantern
#

Yall, Im confused, in this script: https://hastebin.com/share/ozojexamup.java
the noMoreSeeConnector boolean becomes true after a set of conditions have been met. In the debug log, I can see that it does become true, but for some reason, the else if statement doesnt run. I have tested the else if statement without the boolean check and it works fine, so Im confused why adding the boolean check causes it to stop running, even if its conditions are met.

#

ah shit, I figured it out

#

that one was tricky though

pulsar holly
#

How do I make a gameObject's sprite = another gameObject sprite in a randomizer. For context, I'm making a tetris game and want to make a tetromino be the same as the oppentents when it shows up.

dusk apex
#

What have you tried?

pulsar holly
#

I tried using an if statement, but that didn't work.

vagrant blade
#

Be less vague, show your work, explain the issue and errors.

spring creek
#

"Didn't work" is always gonna be an unhelpful response.
And an if statement is going to of course be a part of any conditional logic, but of course not the actual way of changing the sprite.

pulsar holly
#

I'll show the code.

#

And yes, I formatted it!

spring creek
#

This is still really wild, but yeah, formatted way better.

#

So which part of the code is the attempt on the sprite code?

pulsar holly
#

I think line 33

spring creek
#

You should really share the whole thing in an actually halfway decent code site
!code

tawny elkBOT
spring creek
#

I recommend gdl.space most

pulsar holly
#

Again, I formatted it.

spring creek
#

And why did you say your formatted it again?

pulsar holly
#

Because people kept saying I didn't format it when I did format it.

spring creek
#

Ok, yeah, your previous code cut off the color array, so that was very confusing

pulsar holly
#

Oh

spring creek
#

Lmfao

pulsar holly
#

Ok

spring creek
#

So I see you setting the color of the sprite renderer to a random index in your color array. What is wrong with that?

#

You want to change it to an actual sprite?

pulsar holly
#

No, I was just using sprite as an example for my problem.

#

But the thing is, how do I make the oppentents color the same as the players?

spring creek
pulsar holly
#

How do I do that? I don't understand what you're saying.

spring creek
#

Referencing things is a very important and foundational thing to know how to do

night harness
#

Not sure if its better here or editor-tools

With how unity has the "New Script" contextmenu option that makes a default monobehaviour script, can I make and list my own template?

rain minnow
night harness
#

Oh neat! would be cool to add a different one but for now that would work, mind leading a horse to water? 😄

rain minnow
wind jackal
#

new user to unity. i have a college project i’m working on which in the grand scheme of games is quite a basic task. I just need a 3d game with basic features like movement, enemy ai, inventory and a few other things which i’m sure is quite easy for most of you but i’m terrible and no matter how many youtube tutorials i try i always seem to fuck something up so if anyone is willing to guide a complete beginner through the learning process dm please. thanks

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

round creek
#

Can someone explain to me why line 45 causes a NullReferenceException error despite me having the EventManager script execute before this script (through Script Execution Order)? It may be important to note that the EventManager script and this script (GermManager) are attached to the same empty GameObject. EventManager uses the Singleton pattern while GermManager does not. I'm willing to provide more details to anyone willing to help.

leaden ice
#

Also where do you assign EventManager.onEventConclusion?

round creek
leaden ice
#

it should be Awake

#

Start runs so much later than OnEnable and Awake

round creek
#

Doesn't fix it though. I've tried both, and modifying Script Execution Order.

leaden ice
#

It will fix it

#

as long as you also do the Script Execution Order thing

round creek
#

Thanks, it's gone now. I didn't try both (the Awake change and the Script Execution Order) simultaneously before.

jagged snow
#

whats typically used for rotating a character towards a target position with a speed value like rotateSharpness? Quaternion.Slerp? Quaternion.Lerp? RotateTowards?

lean sail
soft shard
#

Im working on a dynamic weather system for my game, starting with rain, though im not sure the best way to handle transitioning surfaces from "dry" to "wet", im using a shader with similar properties to the default lit shader with a "wet value" slider (and other weather-specific params) but this means id have to replace maybe 70% of the materials on most maps and slowly blend between them - what might be a good way to handle this change? Should I make a very large array and add every object in my maps that I want to change the material of? Does it make more sense to put this shader on all surfaces at a "wet value" of 0 even during times where its not going to rain? Or is there maybe a better way to handle this? The idea is for example, is a concrete sidewalk on a sunny day, then it starts raining and slowly that concrete becomes wet/damp/porous, but there are a lot of concrete sidewalks and other surfaces in my maps that should be affected in a similar way

leaden ice
jagged snow
#

thanks

jagged snow
shell scarab
#

what circumstances does colliderField.bounds.size.y return 0 when it's not 0? I think for prefabs it does for example. Any other times?

leaden ice
shell scarab
leaden ice
#

Or the collider is disabled

shell scarab
#

ok that might be it let me see.

lunar python
#

can somebody recommend me a way to handle slopes in platformer correctly?

leaden ice
#

What does correct handling of slopes mean to you?

west lotus
patent rampart
#

Yo guys! I'm trying to make my raycast ignore the colliders of my own player, but I don't want to use layer's as I'm making a multiplayer game, and would still like for the bullet to hit enemies using the same player prefab.

I tried so many things and this is what I have so far.


foreach (RaycastHit hit in hits)
{
    if (hit.collider.transform.root.gameObject != transform.root.gameObject)
    {
        TrailRenderer trail = Instantiate(bulletTrail, bulletSpawnPoint.position, Quaternion.identity);
        StartCoroutine(SpawnTrail(trail, hit));
        break;
    }
}```

It checks if the collider it hit is a collider of a child in the current gameObject's root parent.
However! When there is another player (spawned in with the same prefab, but still it's own root parent), the bullet also goes straight through him?
I have absolutely no idea anymore how I should make the raycast ignore ONLY the player who is shooting and I've tried sooo many things.
anyone have an idea what to do?
somber nacelle
#

just because you are doing multiplayer doesn't mean you cannot use layers. just put only the local player on a separate layer

#

(assuming you are doing this check on the local player, that is)

soft shard
leaden ice
patent rampart
west lotus
patent rampart
shell scarab
leaden ice
#

it would just be whenever you do a raycast

west lotus
west lotus
#

That would be preferable that the state changes cause by swapping materials

patent rampart
leaden ice
#

it would not be possible for any other code to be doing anything between your lines of code

patent rampart
#

oh I never knew that! That's really good to know!

soft shard
# west lotus Oh I think I get it. Yes you would always have the wetness shader on the materia...

Ah I see, thanks for all the feedback! Out of curiosity, how does this "screen space wetness shader" work? Is there any resources that could explain the technical part behind it? What I dont understand is, if its screen space its not actually applied on specific objects in the scene, so how would it know how to turn things wet or dry? Is it based on camera distance or sampling the camera every frame and then applying "filters" above it before it gets rendered over the screen or something?

leaden ice
#

so they can still know how far away a surface is and what direction it's facing

soft shard
#

Interesting, that sounds like a really cool technique

west lotus
#

In deferred rendering there is this thing called the GBuffer that holds material information for all objects, objects first get rendered into that then light is calculated on the buffer. With the technique in question you would modify the normal and roughness values of the buffer after opaque rendering but before light calculations

#

If you search for screen space wetness, GBuffer wetness online you should find a plethora of resources

soft shard
#

Awesome, ill look more into that, thanks again!

lean sail
#

Im thinking about redesigning my object pooling system and could use some tips. i have a singleton pool manager that takes care of all object pools like VFX, bullets, etc. One annoying part is populating the data. I'm stuck either manually linking each prefab in the inspector or letting it create what it needs at runtime when it's first asked for an object, which I feel isnt great. The first time an object is grabbed, itll spawn a lot of them.
As I add more features like "projectiles dont hit the character that spawned it" I feel this system is becoming clunky. I could solve this but I dont want to go deeper into a solution if it isnt good from the start. Im thinking of each character having it's own pool, which would make the above case easier but also enemies on spawn and death will be creating/destroying a lot of objects.
Im not sure if i should remake this or just tough it out with a single pool, anyone have advice on this?

broken light
#

does FindObjectsByType work from an editor script? need to get all objects of type in the scene from my editor script it keeps returning none found, trying it on a monobehavior works fine which makes me think this won't work from editor scripts?

slate imp
#

Hi, i've got a question, is their a way to have multiple Time scales in unity ? like being able to pause the game but still be able to move a free camera with a kind of deltaTime ? If possible is it a good practice to do so ?

fervent furnace
#

maintain your own timescales based on 1

slate imp
fervent furnace
slate imp
#

oh okay thanks

fervent furnace
#

The 1 means unity timescale then you apply some multipliers on it to have your own timescales

cursive kestrel
#

this might sound weird, but is there a way to have a game that simulates at 60 fps but renders at higher framerates ?
Or maybe is there a way to sync all my scripts in a 60 fps loop

stoic ledge
#

Does anyone use Unity 2023? If yes, have you encountered a bug where when you change a field in the inspector, it resets back after deselect-reselect?

scarlet viper
#

I cant invoke from within a scriptable object?

FindObjectOfType<PlayerCharacter>().Invoke("PlaySound", 0.25f);

method works without invoke

gray mural
scarlet viper
cursive kestrel
paper pine
#

how should i post my code when i have multiple files?

gray mural
cursive kestrel
#

is it a good idea ?

#

i'm trying to make a fighting game and i'm trying to implement frame data that is synced at 60 fps

gray mural
#

No, it's usually a bad idea.

#

You won't be able to set your frame rate to 60 fps if it's currently 40.

#

You will be able to set your frame rate to 60 fps if it's currently 80.

cursive kestrel
#

okay

#

so how would you do a 60fps clock

#

that is synced through all scripts

gray mural
#

What is it supposed to mean?

cursive kestrel
#

is there a way for me to call a different functions 60 times per second and that is synchronised through all my scripts ?

#

like script A and B both have a function that they need to be called 60 times per second, at the same moment

primal wind
#

make the loop in a class and have it invoke an event anything that needs it can subscribe to

gray mural
gray mural
gray mural
primal wind
#

This is a simple C# event public event Action SomeEventName

#

You can invoke it from the same class

#

But not outside

gray mural
primal wind
#

I'm pretty sure it doesn't allow you to? At least in my memory

#

I'd need to check again

gray mural
#

You can indeed invoke an event from the another class.

AnotherClass.SomeEventName?.Invoke();
cursive kestrel
#

ok i just read some documentation, now how do i get the event to be called 60 times per second

#

or to be called at a 0.0167 seconds interval

gray mural
thick terrace
#

i don't see the problem with using FixedUpdate at 60hz for this, if the framerate goes below 60 it'll just run multiple updates per frame to catch up, it's designed for that

gray mural
thick terrace
#

for a fighting game with deterministic gameplay, surely yes you do

gray mural
#

Coroutine is enough.

thick terrace
#

i don't know why you'd use a coroutine specifically for this, a coroutine is also limited to running in the same fixed update or update loop, but either way you'd probably want to implement some kind of fixed timestep if you're not using FixedUpdate directly

gray mural
thick terrace
#

if it's running forever in a loop, why not just put it in an Update method somewhere?

gray mural
#

This seems the best option. And more comfortable than using Update with Time.deltaTime added to a variable

gray mural
thick terrace
#

WaitForSeconds also only works if your framerate is 60 or higher

gray mural
#

You may use whatever you want, but coroutines are usually much more readable.

neon junco
#

Next Level Debugger 😄

gilded vapor
#

ah. i'm a really sucker of code

||i'm correct but why error problem here? maybe who can fix i really tired of fix problem error but found on yts||

simple egret
#

And I'm not going to comment on the fact that you're still using JS even though it got deprecated years ago

scarlet viper
#

if i want to execude code after animation finishes, do i have to use events or is a timed Invoke enough? accuracy is important

simple egret
#

Animation Events. That way if you modify the animation you don't have to change a "magic number" in your code

#

Or state machine behaviors, which have a method that gets executed when the state it's attached to exits

scarlet viper
#

youre right

swift falcon
#

How can I draw gizmos on the plane that I created in script? For example, Plane plane = new Plane(Vector3.up, Vector3.zero) and I want this object to be visible by Drawning gizmos. Is this something stupid to want it and should I try something else? I have no idea but this is my intention to see it. I hope I was clear to describe my problem.

lunar python
#

should a GameHandler be a singleton or a static class?

leaden ice
#

other than utilities like Mathf

#

with pure functions and no state

vagrant oasis
#
'MonoBehaviour' instances must be instantiated with 'GameObject.AddComponent<T>()' instead of 'new'
    public Dictionary<int, WikiPost> WikiPosts;
    public Dictionary<string, WikiUser> WikiUsers;

    private void Awake() {
        //Day 1
        WikiPost testPost = new WikiPost("title", "desc", Texture2D.blackTexture, null);
        WikiPosts.Add(1, testPost);
    }
public class WikiPost : MonoBehaviour {
    public string postTitle;
    public string postDescription;
    public Texture2D photo;
    public List<WikiComment> postComments;

    public WikiPost(string title, string description, Texture2D postPhoto, [CanBeNull] List<WikiComment> comments) {
        this.postTitle = title;
        this.postDescription = description;
        this.photo = postPhoto;
        this.postComments = comments;
    }
}
``` can someone help?
#

i want to make a dictionary of WikiPosts

leaden ice
#

pretty straightforward error

#

Is there a good reason you need WikiPost to be a MonoBehaviour?

vagrant oasis
#

if i think about it then no, scripts will get the posts from the game manager

leaden ice
#

Since there is no good reason for WikiPost to be a MonoBehaviour, you should make it not a MonoBehaviour

lunar python
vagrant oasis
#

also i have a question how can i make an enum dictionary, where e.g theres "someUser" = WikiUser("someUser", Texture2D.blackTexture) and so on

leaden ice
#

vague question

vagrant oasis
# leaden ice vague question

like i don't want to make new users each time i want a user to be referenced, so i want them to be made once and referenced in other scripts

charred dock
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

cloud python
#

I meant like I'm starting to feel alright from the break I took from this whole coding thing here

weary swift
#

Yo ! I want to give to a method a data structure that is able to have a variable and a value. In this method there will be a loop that will go through the data structure and will set each variables to their respective values. BUT I want the original value to be changed not a copy of the value (If it was in C I will give a pointer to the variable). How can I do that please ?

fervent furnace
#

is the "data structrue" struct or class
if it is struct then you can pass it as ref=pointer to the variable

weary swift
#

I'm not specifically talking about a struct, for instance it could be a Dictionary or a Tuple but as I saw it copy the variable :'(

steady moat
weary swift
#

Oh ok...

steady moat
#

By example, there is the functional paradigm that specifically handle all case with a return.

spring creek
fervent furnace
#

dictionary is class, but you can still use ref to pass it as pointer to that dictionary

weary swift
# steady moat Alternatively, you can have a "Wrapper". That being said, it is usually not a pa...

My goal is to add what I just said in the message at the end of this method. The idea is to set a number of variables to their respective values when an animation end.

https://gdl.space/wewajozehu.cs

I want to do that instead of using animations Events because I feel like adding each time an event at the end of an animation and defining a specific method to handle what happens at the end of each animation is not really sustainable. Tell me if i'm wrong.

#

!code

tawny elkBOT
steady moat
#

And, I am not sure what you actually want.

weary swift
#

I want to check if a specific animation has ended, if it's the case I want to set a bunch of variables to a bunch of values. For example : Let's say I have a roll animation, I want to wait for it to end and then set for example IsAbleToRoll = true, Blabla = false, Toto = true, etc...

steady moat
#

Are you familiar with what events are ?

weary swift
#

I will look about the StateMachineBehaviour, I don't know what this is and I will come back here if I have questions 👍

weary swift
steady moat
weary swift
#

I know that you can set events in the frames of an animation, but I don't want to use that because it doesn't feel modular and scalable

steady moat
#

C# events

weary swift
#

Oh okay, yes I also know then

steady moat
#

public event System.Action MyEvent;

weary swift
#

I'm not a pro at it, but I know the basics

#

Yes, you can Invoke it and subscribe to it

steady moat
#

What you were asking, the usage of "pointer" can usually be done with events.

reef garnet
#

How do I programmatically change the sensitivity for a cinemachine virtual camera using the POV Lookat and Framing Transposer follow

weary swift
#

But a StateMachineBehavior in my case is close to being the exact same thing as just setting an event in the animation frames ?

#

But just done by code instead of being done by the Unity inspector ?

steady moat
weary swift
#

Ok, so I should avoid my initial idea and go for that ? But this means I will need to create a specific StateMachineBehaviour for each animation (if I want to process something at the end of it ofc) ?

rigid island
steady moat
reef garnet
rigid island
#

i find these statements pretty wild lol

reef garnet
#

nothing that I've been able to find on changing the speed the camera rotates with

weary swift
rigid island
#

show me where you looked

weary swift
#

Ok, thanks for the infos ! Really useful 👍

rigid island
#

and

 **Max Speed**     The maximum speed of this axis in degrees/second.
reef garnet
#

can't find said property in code

#

it's not an exposed variable as far as I can find or it is confusingly named

reef garnet
#

yeah I just found it, but still no info on speed it seems

rigid island
#

speed is acceleration time / maxspeed

reef garnet
#

So I'm basically trying to add a feature where you can change the camera sensitivity, I know how to do this in editor from the inspector but haven't found how to set it in code during runtime

rigid island
#

generally sensitivy is custom float made for custom rotation

#

I barely use the POV

reef garnet
#

I'll get you a screenshot now

rigid island
#

I just use regular cinemachine virtual camera, and rotate that

reef garnet
cloud python
rigid island
#

as MaxSpeed

rigid island
#

cinemachineVirtualCam.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_MaxSpeed = 123;

#

hmm i guess you can try axistate

reef garnet
#

I should be able to manage from here, my main problem was just finding the variable.

rigid island
weary swift
#

@steady moat I did what you said, using the AnimationState and it works perfectly. I just don't like the idea of having to create a separate script for every animations, but this system is still better than all of the others. Thank you very much !

steady moat
weary swift
#

Yes, but if I have a roll animation and a backstep animation, I need to create one for each right ?

steady moat
weary swift
#

Oh...

#

And I can get which animation just ended with the stateInfo variable ?

steady moat
#

That could be a way, but I suggest you either use string, enum or type as "id".

weary swift
#

But let's say I want to invoke OnRollAnimationEnd if the roll ended and OnBackStepAnimationEnd if the backstep ended, how should I differentiate which one ended if i'm using only one script ?

steady moat
#

public class AnimationDodgeEvent : AnimationEvent {}

or

public class AnimationEvent { [SerailizeField] private string id; }

vagrant oasis
#

huh?

buttonScript.profilePicture.sprite = Sprite.Create(post.PostCreator.ProfilePicture,
                new Rect(0, 0, post.PostCreator.ProfilePicture.width, post.PostCreator.ProfilePicture.height), new Vector2(0.5f, 0.5f), 100f);
``` the ProfilePicture is Texture2D.redTexture
steady moat
#
public class AnimationEvent 
{
  public enum MyEnum {
    Dodge,
    Attack,
    etc.
  }
  [SerializeField] private MyEnum enum;
}
weary swift
#

And I do for example AnimatorStateInfo.IsName(rollName) for example ? (if it's a string)

weary swift
#

I'm having a hard time following here sorry

steady moat
#
public class AnimationEvent : StateMachineBehaviour
{
  public enum Event {
    OnEnter,
    OnExit
  }

  private static Dictionary<(string id, Event evt, Animator animator), System.Action action> subscribers;

  [SerializeField] private string id;

  public static void Subscribe(string id, Event evt, System.Action subsriber) 
  {
    subscribers.Add((id, evt), subsriber);
  }

  public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) 
  {
    if(subscribers.Contains((id, Event.OnEnter, animator)))
       subscribers[(id, Event.OnEnter, animator)].Invoke();
  }
}

#

Something like that.

#

You can figure out the details on how to make it works.

weary swift
#

Thanks for thid ! I can't look at this right now, I will tell you when I can 👍

steady moat
#

Ideally, you might want to seperate the actual event and the subscription into two separate class.

weary swift
stoic ledge
#

Is it a good practice to include ALL font assets into the font fallback chain, just in a correct order, starting with static and ending with Dynamic for more obscure characters?

weary swift
buoyant cypress
#

anyone know how to detect/and or resolve packages that have changed to their default state? Client.Resolve() doesn't seem to do this. Client.Add(URL) works (git packages won't be reverted correctly with anything other than URL, not sure about others), but still not sure how to determine if they've been modified.

weary swift
#

Ok thanks, I guess I understand the idea behind it.

tepid brook
#

Hi guys im looking for a bolas like system i have a gameobject between 2 gameobject with rope and i want to rotate the midle object and other follow him someone can guide me to something pls ?

tepid brook
leaden ice
#

Or you could use an asset like Obi Rope

rigid island
#

yeah hinges will do. ObiRope looks cool

tepid brook
#

ok thx guys i will search on that

tall scroll
#

just want to check something before I do a stupid:

public class Target
{
  public void Hit()
  {
    // do smth
  }
}

public class Enemy : Target
{
  new public void Hit()
  {
    // do smth else
  }
}

hit.collider.gameObject.GetComponent<Target>().Hit()

Would still do smth else instead of do smth if it hit an Enemy right?

simple egret
#

I don't think so

#

Use proper inheritance with virtual + override

tall scroll
#

if I overrode it then it would work how I expect?

simple egret
#

Yes

tall scroll
#

oki noice

simple egret
#

If you don't plan on having any logic in Target.Hit(), consider making it abstract

tall scroll
#

Noted I do but good to know for the future

leaden ice
#

if you did a proper override... oh SPR2 sorted you out
But you'd get do smth else in both cases if you override properly. (assuming it's actually an Enemy)

tall scroll
subtle basin
#

To create a speed effect in my 2D game, I want to stretch and shrink the player's view in the direction they are walking. How to do it?

latent latch
#

uv manipulation

#

maybe can get away with messing with scale transform values

indigo verge
#

In the editor, when you drag an object into your scene, it snaps to other objects that the mouse is hovering over, without overlapping them. Is there a way to replicate this functionality in a runtime scenario?

#

I've been doing research to try and find something like it, but I can't seem to find anyone implementing something like this.

cunning meteor
#

i use this scriped for playing animations walk1 is a walking animation ,walk is a idle animation but when i pres a and d both at the same time it doesnt go back to the idle animation(walk): if (Input.GetKeyDown("d"))
{
Debug.Log("hi5");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("d"))
{
Debug.Log("777");
transainimation.SetTrigger("walk");
}
if (Input.GetKeyDown("a"))
{
Debug.Log("hi");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("a"))
{
Debug.Log("888");
transainimation.SetTrigger("walk");

rigid island
#

@cunning meteor dont crosspost

cunning meteor
#

alr

broken light
#

how do you serialize a graph that has references to gameobjects in a scene ? im using callback reciever interface, i dont know how to keep it all linked

soft shard
# indigo verge I've been doing research to try and find something like it, but I can't seem to ...

That is a mechanic often seen in building games like RTS, TD, etc (you can try looking up these genres for more research), though the general idea would consist of firing a raycast from the mouse screen position to the world position, and placing an object at the hit .point, if the pivot of the object is at the base then that should be all youd need to do, if it is in the middle, youd want to consider adding half the height of the mesh bounds or collider bounds to the hit .point before placing it - you can take it one step further and snap it to some kind of grid if you dont want to allow freeform placing, RTS games tend to do grid snapping, TD games tend to allow freeform since RTS tend to be about managing limited resources and TD tend to be about maxing the landmass, but every game is different

indigo verge
#

I just need to make sure that all of my items have some kind of definition of where their pivot point is.

soft shard
# indigo verge So as long as I have a pivot point, just use that? That's much simpler than wha...

Sounds cool! But seems like you got th general idea, yeah - though if the object does have a rigidbody and you dont want the thing your placing to move around aftter placing it (or you want to create a "preview" or "ghost placement" to see where you would place it without committing to placing it there), you may need to set your rigidbody to kinematic, sleep the rigidbody or freeze its constraints (or possibly disable the collider so physics dont have anything to react to)

indigo verge
#

Yeah, all my items will be kinematic, since I do need them to not be influenced by physics

#

the rigidbody is purely for hit detection, in terms of its actual functionality

soft shard
#

Raycasts can hit colliders without rigidbodies as well, so if you only need it for hit detection, you may not even need the rigidbody at all

vapid lynx
#
        

        List<SourceVertex> filteredVertices = new List<SourceVertex>();
        List<int> filteredTris = new List<int>();
        for (int i = 0; i < positions.Length; i++)
        {
            Vector3 vertexPosition = positions[i];
            float vertexHeight = positions[i].y;

            if (vertexHeight >= 5 && vertexHeight <= 10)
            {
                filteredTris.Add(sourceMesh.triangles[i]);
                filteredVertices.Add(new SourceVertex()
                {
                    position = vertexPosition,
                   
                });
            }
        }
#

Im trying to make grass on the GPU

#

and i have the array of verticies and triangles

#

however I wanted to only have grass for a certain height range so i was tryign to filter it

#

but when i added the filteredTris thing, my unity completly crashes

cosmic rain
vapid lynx
#

yeah

#

wait i think it might be a index out of bounds error

#

coz im assuming that sourceMesh.triangles is the same size as positions

cosmic rain
#

The editor shouldn't crash even if your scripts throw an error.

vapid lynx
#

oh

cosmic rain
#

Where is that code running?

vapid lynx
#

in a grass generator script

somber nacelle
#

is the editor actually crashing or is it freezing? because those are two different things, and which the latter is usually caused by your code

vapid lynx
#

Oh wait

#

i meant freezing 😭

#

my bad

somber nacelle
#

that typically indicates an infinite loop

vapid lynx
#
        int[] tris = sourceMesh.triangles;
        SourceVertex[] vertices = new SourceVertex[positions.Length];
        for(int i = 0; i < vertices.Length; i++) {
            vertices[i] = new SourceVertex() {
                position = positions[i],
            };
        }```

this is the original code. The only problem is that it covers my entire terrain mesh and i only want it to cover over a certain height
#

so how would i go about doing it in a way that like works

cosmic rain
#

As for the implementation itself, I'm not sure if modifying a mesh like that is gonna produce the results that you expect.🤔

vapid lynx
lean sail
modern creek
#

Like obviously object pooling is great for things like bullets that are relatively "simple" with limited logic but you're spawning potentially millions of them over a session.. but even for vfx, I dunno, it seems like maybe it's a close call whether the additional complexity and load costs are worth it

#

bullets I'd say are good pooling candidates, but .. maybe the other stuff isn't until you're talking like N > 100k+ in a session..

#

i dunno .. like in my merge game I create several items per turn that have lots of initialize logic.. shaders.. material cloning.. vfx and particles, sound clip allocation and playing.. and it's pretty invisible even when the user is mashing moves at 2-3/sec

#

even with editor overhead i've never dipped under 60fps or any GC burps

#

i tried to mash through that level as fast as i could to demo

lean sail
# modern creek How many of these things are we talking about? I spawn VFX (with instantiate, fr...

its hard to estimate since i havent planned a whole lot but definitely not near 100 a second. im making a roguelite, enemies likely will cast abilities every few seconds, planning on having a max of like 50 enemies at a time.
I probably dont need pooling, but im also scared of running into a case later when im really deep into the project and suddenly start needing it. Then having to implement it on everything

modern creek
#

each one of those tiny little prefabs has like.. 500+ lines of init code, instantiating and copying materials, vfx, nested prefabs etc.. and i've just never needed to touch optimization

#

I'd probably KISS here and not pool until it's a problem

#

object pooling is great but it's definitely adding a layer of complexity when the cost/benefit might not be clear at the outset

#

imho stuff like this (maybe even localization) is best added when you need it

#

i don't even think retooling to take an Instantiate() approach and moving to a pooling approach is that big a deal

lean sail
#

Ah you're probably right. Ill likely just drop the pooling entirely for now because this really is such a pain. Im pooling an object thats likely gonna be cast once every 10 seconds

modern creek
#

and if you get to the point where you are seeing some performance issues.. at least at that point you can crack open the profiler and examine what's going on.. maybe some errant Resources.Load() call you forgot about or whatever.. and if you just can't get any faster then.. explore the pooled approach imho

#

yeah overengineering a perfect solution is a ... tempting forbidden apple in gamedev.. my opinion is that you kinda gotta get something into market/finished before you worry about the tech stuff like that.. even accruing some tech debt with the benefit of getting shit done is worth it imho

#

like.. the other day my game designer asks me for a list of all the levels (some 600+) in our game with the 1-star/2-star/3-star moves required since the admin tool makes editing a single level easy but not reporting on all the levels at once

lean sail
#

It just feels wrong to be instantiating and destroying so much, but maybe ill just run some tests to prove to myself its not a problem

modern creek
#

my brain starts going.. ok, I can make some denormalized json reporting object that'll get uploaded to our reporting/analytics database, polled once per day.. plugged into google drive

#

and he's like NO NO NO do THIS

#

that code took like 4 minutes and he's like BEAUTIFUL I LOVE IT

#

and meanwhile i'm like 🤮

#

point is.. Instantiate() or even Resources.Load() aren't terrible in small doses, or even before you know you have a problem.. cuz kind of the worst outcome is you spend hours/days/weeks architecting something complex and beautiful and fully featured but then it wasn't even necessary

lean sail
#

Yea true, i guess if i have problems itll likely be from certain overused attacks anyways which I can just make dedicated pools for.

#

not my one off, 30 second cooldown ultimate ability

modern creek
#

or even if it's a huge problem, make the attacks like that use different kinds of bullets instead of 100x bullets

#

like a beam

#

(dunno exactly what your game is but hopefully you get the point.. like.. just change the ultimate a tiny bit to not need 1000 of a small thing)

#

"hit everything on the screen 6 times"

lean sail
#

thats a pretty smart idea, just like a single beam and change the damage rate of it

#

yea my game is just a simple 3d roguelite, you go around and shoot things. items will buff the players and they'll likely get a lot of buffs to the point of possibly having 50x the initial attack speed

modern creek
#

yeah maybe... depending on how many bullets every enemy is shooting at you (like, is this a bullet hell, or is it more like.. uh.. i dunno, something less ha) you might actually need to pool

#

Instantiate is expensive but .. not too bad, and having all the logic constrained to a single bullet/player/npc/turret without needing to do all the pooling "gimme a bullet and set it here and tell me when it hits something and set the owner/properties/speed of it" would be nice

#

if you are pooling, though, i'd probably just have a single pool for bullets, with a BulletManager static/singleton and some methods to get a bullet (and have the bullets do the collision checking and returning themselves to the pool)

#

basically your enemies/players/turrets/whatever should basically not have to do any of the plumbing - just "get me a bullet, set it to (x,y) with a velocity of (x,y) and a damage of (x)" and then forget about it

rigid island
#

use Path.Combine

modern creek
#

no :p

#

I ran that chunk of code exactly one time and then threw it away 🙂

lean sail
modern creek
#

I mean.. obviously I could [over-]engineer the crap out of this little thing.. store the path in player prefs, prompt the user for it, save the output in a document and put it in the database, etc etc etc.. but the 10 line csv solution that took 5 minutes was what the designer needed/wanted and then we were back to other problems 🙂

modern creek
#

whatever is shooting or getting hit by the bullet shouldn't need to do a lot of boilerplate nonsense to get/destroy a bullet

#

i dunno exactly what that looks like for you, but maybe it's a callback on "did hit the player" or some interface that all your shootable/hittable things implement in order to interact with bullets (ie class Player : IHittable, IShootable where hittable has a "GotHit" callback or something, shootable has some things like "shooting direction" or "shooting velocity" or "shooting damage" or whatever), then the player just calls Shoot() and the bulletmanager does all the repeated boilerplate code

lean sail
# modern creek Yeah so ... despite my previous diatribe I'd actually say you're probably on the...

yea but this kinda brings me back to the initial problem. its really annoying to populate this pool. I could populate it when its first asked for a certain prefab and really i might just do that but over time rather than instantly.
and yea the pool right now is also pretty easy to use, its a 1 line solution for anything to get an object. then the object itself is responsible for returning itself to the pool

modern creek
#

why's populating the pool expensive? Aren't you doing this like, once per game session or level or something? I mean, I feel like even if your game is pretty "busy" you only need like.. 1k? 10k?? bullets in the pool

#

even instantiating 10k items in the pool once should only be a few hundred ms... maybe, depending on what each bullet needs to do

royal birch
#

Hi I wonder if somone can help me pls? How do I change an objects physics layer mask after instantiation? The prefab is built as "ignore Raycast" for instantiation but then needs to be switched back to "default" after instantiation.

rigid island
#

or something

lean sail
# modern creek why's populating the pool expensive? Aren't you doing this like, once per game s...

i mean that either i have to manually drag in each object to this pool in inspector, or I can populate the pool manager when something asks for an object for the first time. Basically a difference of doing it in awake vs doing it on demand. Im just unsure if doing it on demand will suffice, because throughout the game there will be new enemies so this will constantly be spawning 100s of objects as the game goes on

modern creek
#

Hm, I guess I don't understand? Maybe show me a screenshot of your inspector pool or some code about how you're getting these pooled objects? It sounds like you're doing something (process-wise, not theoretically) incorrect

#

Like, don't you just have some class BulletManager that's got an Object Pool on it, you instantiate a boatload of the bullets at app/level startup, but then you just GetPooledObject() (or whatever the method is called) whenever you need a single bullet? .. you shouldn't be adding more items to the pool at playtime runtime unless you've suffered some pool starvation, in which case you'd need to just adjust up how many items the pool is making at the beginning

lean sail
royal birch
modern creek
#

wait - are you only instantiatng "prewarm count" bullets?

lean sail
modern creek
#

bullets/explosions/hittexts etc

#

show me more code on your ObjectPoolManager - like, show me where you GetPooledObject

lean sail
modern creek
#

yeah it should be like 100-1000 i imagine.. maybe hittexts/explosions/healtexts are like 50, but bullets probably 1-2000

lean sail
#

it works pretty nicely, but populating this in inspector sucks

spring creek
lean sail
rigid island
#

Unity does that for NetworkManager in NGO i start doing it too

modern creek
north hearth
#

Does anyone have any idea why my Heating subclass is not in use by any asset. The subclass is not separated from the base class by another script. They are both sitting in the same script which is already attached to a game object.

modern creek
#

Like, I always thought you slapped an object pool component on something, then did the instantiation of the objects yourself, not create the component yourself with initializers to actions/funcs

cosmic rain
modern creek
#

Like maybe I'm missing something obvious, but it seems like your singleton is creating an object pool at runtime, not populating an object pool that you've defined

lean sail
#

and it does get filled through the create function line 63

modern creek
#

Like why not just make an Object Pool that has some RBProjectiles on it, you instantiate your 100 or 1000 at awake time, then everything in the game just says RBProjectileSingleton.GetMeABullet() and the singleton just does RBpool.GetPooledObject()

#

it doesn't look like that to me? it looks like lines 63-75 create a function that you send as a parameter on line 95

north hearth
modern creek
#

so your singleton creates an object pool that is empty and not initialized

lean sail
#

the pool itself works and has all the objects that i want, its just that it is tedious to assign the references for which object it should spawn in inspector

somber nacelle
modern creek
#

hm.. ok.. I'm probably missing something .. not sure what though 🙂 Sorry that's not more helpful

cosmic rain
modern creek
#

At a glance though, it does seem a bit more complex than needed - aside from bullets.. like I'd use hittexts and healtexts and VFX like explosions just as needed until playtesting shows otherwise

lean sail
modern creek
#

i have this hittext thing which I'm assuming is pretty close to yours.. basically you spawn it at some location and it just rises up over 0.5f sec and tweens the color from whatever to whatever... does some material stuff, some random angle/heights/etc so they don't overlap.. i've spawned hundreds of them on the screen at once and it hasn't been a hotpath thing

north hearth
modern creek
#

I'd probably rearchitect your singleton to just be a bullet manager - and the api surface the rest of your game essentially consumes is public Bullet GetBullet() and then returns it to the pool with bullet.gameObject.SetActive(false) which, my understanding, is how you do it (instead of destroying it)

somber nacelle
lean sail
finite otter
#

Can anyone help me with my textures theyre messed up

modern creek
#

at least that way, you only have to "solve" the pooling problem once, and the rest of your game ultimately doesn't care about how a bullet is created/destroyed

cosmic rain
modern creek
#

here i am, smoothbrained putting one class into multiple files, not putting multiple classes into one file 🤯

#

😉

cosmic rain
#

Heh, poor C++ coders have to split each class into 2 files.

modern creek
#

I learned on C++.. PTSD from .h files

north hearth
lean sail
north hearth
rigid island
cosmic rain
finite otter
rigid island
north hearth
cosmic rain
cosmic rain
rigid island
north hearth
#

Actually

#

Oh my lord

#

I can just use a bool to get it fixed

#

And then do an early return

cosmic rain
#

Also, if your child class does not use(does not need them assigned) any of the fields in the base class, inheritance is a very poor choice imho.

north hearth
north hearth
#

I'll just use bools to get it fixed

#

I have no idea why I didn't think of that

#

I struggled with this for over a day

#

I am actually angry now

#

But thanks for helping

thin kernel
#

Hi. I want to make a client for a multiple unity games, but they should be embedded inside (unity window inside client window). What engine can I use for the client? I cant find a solution for unity game inside unity game, wpf seems to work only for windows, and flutter only for android and ios.

rigid island
#

MAUI is cross-platform

#

or make it a webapp with asp.net core

mortal egret
#

heyy could anyone help me with a bug Im having in a 2d platform game?

spring creek
mortal egret
#

Thanks, basically I have a moving platform and a Player, when the player jumps on top of the moving platform I check the colliders and I parent the moving platform to the player so they both move together, however when I try to move the player the movement is all stuttery

#

I have tried adding the velocity of the moving platform to the player, however its slow and stuttery

spring creek
#

And what do you do for the platform?

mortal egret
#
private void FixedUpdate()
{
    _onGround = _collisionDataRetriever.OnGround;
    _onMovingObject = _collisionDataRetriever.OnMovingObject;
    _velocity = _body.velocity;

    _acceleration = _onGround ? _maxAcceleration : _maxAirAcceleration;
    _maxSpeedChange = _acceleration * Time.deltaTime;
    
    if (_onMovingObject)
    {   
        _desiredVelocity = new Vector2(_direction.x, 0f) * Mathf.Max(_maxSpeed + _collisionDataRetriever.MovingObjectVelocity -         _collisionDataRetriever.Friction, 0f);
    }
    _velocity.x = Mathf.MoveTowards(_velocity.x, _desiredVelocity.x, _maxSpeedChange);
    
    _body.velocity = _velocity;
    Debug.Log(_body.velocity);
}

I check if Im on moving object, if yes, I do a new desired velocity, where I add the movement speed of the platform

#
_desiredVelocity = new Vector2(_direction.x, 0f) * Mathf.Max(_maxSpeed - _collisionDataRetriever.Friction, 0f);
#

for obstacle move, i have a parent which holds the script, a child that is the platform itself with rigidbody etc, and a list of points in which platform goes to

spring creek
#

Ok, so fairly complex movement, but rigidbody velocity based.

vivid raven
#

im trying to make a name tag that follows my player, im using text(TMP) but nothing working. ive looked up stuff on yt and cant find anything. heres the code i have right now ``` public class gotocat : MonoBehaviour
{
public GameObject cat;
public Vector3 moveup;
public float up;
// Start is called void Start()
{
moveup = new Vector3(0.0f, up, 0.0f);
}

// Update is called once per frame
void Update()
{
    transform.position = (cat.transform.position + moveup);
}

}```

mortal egret
#

yeahh and I think the fact its rb velocity based is screwing something up

spring creek
#

Have you set the players rigidbody interpolation setting to interpolate?

mortal egret
#

yes

mortal egret
vivid raven
vivid raven
#

at least i think it is

spring creek
mortal egret
#

No, still the same, if anyone could come voice chat I think it would be easier to show, thanks for the help

vapid lynx
#

How do i make it so when i do fullscreen, the healthbar stays like realtive in size and stuff

chilly surge
#

Take a read on Canvas Scalar component and the different scaling modes, and see which one is the one you want.

vapid lynx
#

thx

north hearth
#

Ignore the access modifiers

chilly surge
#

Using switch on (presumably) a bool is, unconventional to say the least.

rigid island
#

lol ohmy

north hearth
#

Unconventional in what way

chilly surge
#

In that you can just use if.

north hearth
#

I'm aware, I don't really use them unless I have to

somber nacelle
#

but why would you use a switch statement here instead of just an if statement? 🤔

north hearth
#

That's literally the only reason

somber nacelle
#

that's not an answer as to why you chose to use a switch statement

#

that's why you refuse to switch to an if statement

north hearth
#

I prefer the aesthetic of switch statements haha

#

That's it

rigid island
#

lol wut

lean sail
#

seems more like someone just learned what a switch is 😄

somber nacelle
#

ah yes, extra boilerplate. such aesthetic lmao

mortal egret
#

thats actually so funny

north hearth
somber nacelle
north hearth
#

Maybe that explains

somber nacelle
north hearth
rigid island
north hearth
#

😆

inland lion
#

These mobile controls do not work, the textures are white and can’t move, is there a way to fix it?

plucky inlet
inland lion
#

Oh

#

Which channel do I put this in?

plucky inlet
#

Probably UI for a first attempt and see, if its related to that. but still, put more info. Does it work in editor, did you try anything to debug yet and so on.

inland lion
#

Okay.

#

I think the scripts are broken or something, I opened a deleted Rip-off game I had for years and it just showed up like that.

plucky inlet
# inland lion

you know how to debug? like check the console and so on?

inland lion
#

Not sure, I’m kinda new to scripting in unity.

plucky inlet
inland lion
#

Ah ok. Ty!

#

Do I talk about the problem there and ask how to fix it?

plucky inlet
#

You first check yourself, if you get any errors and if its working in editor and so on. investigate to provide something people can work with

inland lion
#

Ah

#

There’s this at the bottom

plucky inlet
#

so we should stop spamming this channel here. and its def. not a coding issue. your game is super outdated. Google for the error, short said, your systems used are no longer being used by newer editor versions. #📲┃ui-ux

inland lion
#

Ohh.

dense swift
#

anyone have experience with github? I'm having issues to the point where I cant work on my college project at all and its stressful 😭

plucky inlet
quartz folio
dense swift
#

I was just asking if anyone had experience with github as an preceding question jeez, also I know it's not exactly code related but I wasnt sure where to ask @plucky inlet

spring creek
#

No one wants to commit without knowing what it is about. Nor should they

#

The "is anyone experienced" question is just always harmful

Hope that helps! Nothing mean was meant by it

dense swift
#

That's fair, well anyway then, it seems like I'm not able to fetch the origin because of some interuption that happens mid-unpacking process. I already tried restarting my computer and router, as well as logging out and back into github desktop so I'm not sure what to do. I can't work on classwork without it so I'm a bit stressed apologies if I came off rude at all. Also, this is one of the error codes I got: "remote: Enumerating objects: 45, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (7/7), done.
error: RPC failed; curl 56 Failure when receiving data from the peer
error: 1435 bytes of body are still expected
fetch-pack: unexpected disconnect while reading sideband packet
fatal: early EOF
fatal: unpack-objects failed"

plucky inlet
tender plume
#

Does anyone know how to make it so when I pause a Timeline, the animations on Animations Tracks animating the characters keep looping instead of freezing, here's the snippet of code that is pausing the Timeline:

public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        if (firstFrameHappened && Application.isPlaying)
        {
            //director.SetSpeed(0d);
            director.Pause();

            unpauseAction = () =>
            {
                //director.SetSpeed(1d);
                director.Play();
                dialogSystem.continueEvent.RemoveListener(unpauseAction);
            };
            dialogSystem.continueEvent.AddListener(unpauseAction);
        }

        firstFrameHappened = false;
    }```
I have been, no joke, looking for a solution for 4 hours and none of the google results work, you guys are my last hope before I decide it's not a bug and it's a feature
#

here's how the timeline looks

plucky inlet
tender plume
#

already saw that thread like

#

10 times

#

ALTHOUGH

#

maybe I could download the project of those examples

#

(which I didn't do because it was like 7 years old and it would be a hell to import)

plucky inlet
upper pilot
#
        for (int i = 0; i < GameDatabase.Instance.ItemList.Count; i++)
        {
            button.onClick.AddListener(() =>
            {
                Game.Instance.inventoryManager.AddItem(i);
            });
        }

Seems like this works like in JS and all butttons will call AddItem() with index being equal to .Count
How do I make sure that each button has its own index passed through onclick event?

fervent furnace
#

copy the i to local variable

#

or make a custom struct/class and capture the variable by your self

plucky inlet
#

Your code currently adds a listener to one button for all items?

#

Why not make the button a prefab and create it from script, so you already have a loop you could hook into and pass in the correct item?

upper pilot
plucky inlet
#

so you got it working?

upper pilot
#

Yes

#

That wasnt the issue, I did what the other person said and created a local variable.

chilly surge
#

Quite a common problem in a lot of languages

#

Go specifically added a language level fix for this problem somewhat recently.

silver chasm
#

there is no remove button in the package manager. does anyone know how to remove the package. we want to remove photon

silver chasm
#

from package manager

primal wind
#

Regular assets don't have a remove button. Only packages

#

You basically just delete them manually

#

For clarification regular assets are what you're importing from the My Assets tab

#

Almost everything else is a package

silver chasm
#

ok

#

so photon is a regular asset?

plucky inlet
#

If its only in your project folder but not in package manager, its an asset and you can get rid of the folder

tawny gale
#

Anyone know how can I load dlls at runtime and add it to the project like if I have a assetBundle that as a script in a gameobject called Potato.cs and I compile that script outisde of the main project then import it with assembly.load how can I make it be acessible in the unity project. Because I want to make my game moddable more or less like KSP or city skylines.

primal wind
#

It's easy and complex at the same time. Look into BepInEx

#

I'm sure you can implement it directly

#

Tho it doesn't have sandboxing

tawny gale
#

It doesn't need to have sandboxing

#

So it's ok I will look into BepInEx

plucky inlet
#

You guys got an idea about why ToJson might give me {} in a custom editor script but not on runtime? Like, the object is there and I can access the list, but ToJson does not seem to like the list when in editor mode. Is there a parameter I am missing to make JsonUtility work in editor scripts?

primal wind
#

JsonUtility is pretty weird. Plus most people just use Newtonsoft.Json as soon as something doesn't work

plucky inlet
late lion
plucky inlet
plucky inlet
plucky inlet
thin aurora
#

JSONUtility's shittyness strikes again

tawny gale
#

What I want to do is import the asset bundle and compile then add the dlls so they are recognizable in the scene of the asset bundle

thick terrace
tawny gale
#

Ok, but how should I approach the creation of the plugin system?

#

because a lot of games don't use the approach of bepinex and compile the scripts at runtime one of the examples is KSP

#

and it uses dlls, asset bundles for the mods I wanted to create something similar so the players don't need to install third party things

thick terrace
#

you can do pretty much anything that isn't creating new unity scripts, so decide what you want modders to be able to customize and create some base interfaces in the game that modders can implement in a plugin

tawny gale
#

But a lot of games can add unity scripts It's not impossible to do it but I don't find how can I do it I'm trying now to build a asset bundle with a .asmdef that I read on a thread that could work

thick terrace
#

sure you can do it, you just have to hack some unity runtime stuff to make it work, which is what bepinex does

tawny gale
#

Yhea and that's what I wanted to understand

primal wind
#

Simplest answer is, create a base class for your mods and when you load the assembly of a mod which uses it, you can load it directly

#

It's essentially what BepInEx does outside of injecting itself into Unity

#

And managing dependencies

#

BepInEx's plugin class is basically a MonoBehaviour. When the game loads, it loads all mods that can be loaded (have the base class and all dependencies satisfied) and add them to a manager GameObject. You can typically see it if you use UnityExplorer in a game with it

static matrix
#

I was checking out the profiler and was noticing I was spending a lot of perf on my physics checks, (which I use to check what creatures are near the caster, there are a lot of casters)
and was wondering if it may be more optimal to just iterate through all the creatures and check the distances? or would this be more perf heavy

west lotus
#

Depends on the number of creatures

#

And what physics check you are using

#

And also why a physics check

static matrix
#

im using Physics2D.OverlapCircleAll
number of creatures is like uhhhhhhh
50-100 i think

fervent furnace
#

linear scan how many times?

west lotus
#

And how many casters ?

plucky inlet
west lotus
#

Cause that will multiple for each one

static matrix
#

im using physics because its what I thought was the way to detect all the things that are near something

plucky inlet
static matrix
#

this isn't for the player, its also checking other creatures to see if it needs to switch state to fearing or hunting etc

west lotus
fervent furnace
#

your physical query cant help you to reduce search space, try reduce the overlap radius, if this not work then the only way is to use your own space partitioning/BVH, then perform nearest neighbor search
i realize i havent written my own BVH though

static matrix
#

okay good to know then
i'll try the distance check

west lotus
#

Also consider not doing it every frame or consider splitting the work over multiple frames

static matrix
#

async scary

#

but ill look into it

plucky inlet
#

not async, just not in plain update 😉

#

What about the creatures just adding and removing themselves to a static list when in range for example and do a simple vector distance on themselves against the player? Any issues performancewise?

west lotus
#

I was referring to the good old time-slicing technique. For example in our game we have on average anything between 6k and 10k shooting positions for the enemies to take. Obviously we don’t update each and every one every frame

tawny gale
fervent furnace
#

it is linear scan, ever worse than using physical query to limit search space

static matrix
plucky inlet
#

Ah, just read your post again and you have multiple casters and multiple targets (creatures). Well from that part, I agree with having something like a grid system or similar

granite light
#

CommandInvokationFailure: Failed to update Android SDK package list. C:\Program Files\Unity\Hub\Editor\2021.3.37f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\cmdline-tools\2.1\bin\sdkmanager.bat --list

Error: Could not find or load main class Files\Unity\Hub\Editor\2021.3.37f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\cmdline-tools\2.1\bin\\.. Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

I am building to quest3

static matrix
#

isn't quest vr?

plucky inlet
static matrix
#

before:

 var IsNearFear = Physics2D.OverlapCircleAll(transform.position, FearCheckRadius);
        bool HasFear = false;
        foreach (var item in IsNearFear)
        {

            if(item.gameObject.GetComponent<Creature>()){
                if(Fears.Contains( item.GetComponent<Creature>().MyColor)){
                    scruffState = ScruffState.fearing;
                    HasFear = true;
                }
            }
        }


after:

 var IsNearFear = GameObject.FindObjectsOfType<Creature>();
        bool HasFear = false;
        foreach (var item in IsNearFear)
        {

            if(item.TryGetComponent(out Creature c) && Vector2.Distance(transform.position, item.transform.position) < FearCheckRadius){
                if(Fears.Contains( c.MyColor)){
                    scruffState = ScruffState.fearing;
                    HasFear = true;
                }
            }
        }
#

this is probably faster maybe hopefully

plucky inlet
#

Oh my god, do not do a FindObejctsOfType everytime

#

Get a list going somewhere and your creatures register themselves to it. So you got something to iterate over

static matrix
#

good idea ig

plucky inlet
#

Also the trygetComponent. Just be sure your creatures have the script and your list being of type Creature. soy ou can save that call too

fervent furnace
#

what "Fears" is?
dont tell me it is a list of >100 elements

static matrix
#

"Fears" is the list of colors it is afraid of
its like 4 elements long, Color is an enum

fervent furnace
#

list of 4 elements is fine
the previous version is definitely better, iterate all vs iterate some of them
also use the overloaded version of overlapcircle which takes a list as buffer

static matrix
#

ah whats the overloaded version?

plucky inlet
#

I suggest to just write the most performant of both versions and see, what your profiler does

#

If you do not need physics at all, you could just remove it entirely from your project. But if you need it, you can still try to use overlapsphere and update from there. But as you already tried with your casters and creatures, your outcome was performance issues, right?

dawn mauve
#
[MenuItem("Build/Build Linux Game Server")]
public static void BuildLinuxGameServer()
{
    if (!Directory.Exists(LinuxGameServerBuildDirectory))
        Directory.CreateDirectory(LinuxGameServerBuildDirectory);
    var report = BuildPipeline.BuildPlayer(
        new BuildPlayerOptions
        {
            scenes = GameScenes,
            locationPathName = Path.Combine(LinuxGameServerBuildDirectory, LinuxGameServerBin),
            target = BuildTarget.StandaloneLinux64,
            options =  BuildOptions.Development, // currently this is the only way to see logging
            subtarget = (int)StandaloneBuildSubtarget.Server
        }
    );
    if (report.summary.result != BuildResult.Succeeded)
    {
        Debug.LogError($"{report.summary.result} Server build failed with the following details: {report.summary}");
        return;
    }
    Debug.Log("Server build succeeded and is located at: " + Path.Combine(LinuxGameServerBuildDirectory, LinuxGameServerBin));
}
docker run --platform linux/amd64 -it --rm $(docker buildx build -q --platform linux/amd64 -f $(git rev-parse --show-toplevel)/unity/UnityGame/LinuxGameServer.Dockerfile $(git rev-parse --show-toplevel)/unity/UnityGame)

Is there a way of seeing logging (Debug.Log and/or Console.WriteLine) in a non-development game build? The only way I've found I've been any to see logs from my monobehavior is to set BuildOptions.Development for BuildPlayerOptions (see code above). When that option isn't present, I don't see logs anymore in the game server. Since I'm on an m2 macbook, it's unclear to me if that's because logging is silenced on non-development builds or if its because there's an issue running the binary

plucky inlet
knotty sun
plucky inlet
#

I agree, thats the simplest way if you do not rely on internal unity logs

dawn mauve
dawn mauve
plucky inlet
#

From what I know, debuglogs get fired no matter the debug bool is on or not for built. so that would work

dawn mauve
plucky inlet
#

Not sure about the current way or if it still applies. I am always using IDE or any UI to output what I need

thick terrace
oak ore
#

Hey, I am doing a drag item from inventory function and have the drag script like this. When it hits a certain hitbox it goes back to its original place. But I've ran into many problems, sometimes the items disappear when they get dragged after a change of scene, or the original position is never (0,0,0) (the items are attached to a gameObject) and after dragging it many times it starts shifting from its original place. Any help?

oak ore
dawn mauve