#archived-code-general

1 messages · Page 333 of 1

harsh rapids
#

ah

#

here

#

i think ur right, device 1 run on 60 and device 2 runs on 150

main shuttle
#

Isn't readable on the phone. That's why the bot message dump sites are better.

harsh rapids
#

oh

#

which one is it

main shuttle
#

All of them are better.

harsh rapids
#

i used hastebin

#

the code might be a bit messy sorry

main shuttle
#

A bit yeah xD

harsh rapids
#

the original dude working on this project left and here i am with this mess

gray mural
#

3 resolutions? So the List validResolutions just contains 3 items? It gets the items from Screen.resolutions if the option IsValid and the dropdownOptions don't contain it

leaden ice
harsh rapids
#

any suggestions on what to replace it with

leaden ice
#

Nothing

#

Remove it

harsh rapids
#

oh

#

ok

leaden ice
#

You will need to reduce the speed to compensate

harsh rapids
#

yeah thats alright

leaden ice
#

But now your speed variable will make sense as meters per second

harsh rapids
#

ahh

leaden ice
#

Mouse input should also not be multiplied by deltaTime

harsh rapids
#

thanks a lot

#

holy shit its so fast

leaden ice
#

Basically the person who wrote this didn't know what they were doing and just thought to throw deltaTime everywhere willy nilly. This is a mistake

main shuttle
#

And the Lerp part and clamping looks weird to me too.

velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
if(!dashFlag)
{
  if(velocity.magnitude > moveSpeed)
  {
    velocity = Vector3.Lerp(velocity, velocity.normalized * moveSpeed, deceleration);

Not sure if this will give you the thing you want to be honest, this whole code is weird to me.

harsh rapids
#

tysmm ur a lifesaver

harsh rapids
fallow quartz
harsh rapids
#

when i click on C# files why do they open in individual windows instead of the same one but as a tab?

main shuttle
harsh rapids
main shuttle
# harsh rapids

Hmm, there isn't even a project in here.
Do you open these scripts in Unity?

harsh rapids
#

like they are in seperate windows

harsh rapids
#

pretty sure they supposed to appear here

main shuttle
tawny elkBOT
harsh rapids
#

i just installed unity

#

normally

#

pretty sure vs code is like default?

main shuttle
#

No, you can install visual studio via the Hub, not visual studio code.
And then still, you would need to follow the bot's setup advise.

harsh rapids
#

ohhh

#

my bad

#

thanks a ton

fallow quartz
#

what is this?? never got it before

somber nacelle
#

That's the editor crashing

static matrix
#

how can I optimize physics2d.findnewcontacts?

fallow quartz
leaden ice
#

Could be almost anything

somber nacelle
#

How should I know what caused it? You provided no context, just a screenshot of the progress bar for the crash

static matrix
#

code will just cause it to freeze, if you have infinite recursion or something

fallow quartz
#

and know i open and i can upload without any problem

static matrix
#

theres probably a crash log 🤷

somber nacelle
#

Check the !logs to figure out what may have caused it

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

fallow quartz
#

now what should i do

static matrix
#

but yeah how could I optimize physics2D.FindNewContacts

fallow quartz
#

0x00007FFC7B3AD0A2 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B383081 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B3662F5 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B369532 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B32340C (FirebaseCppApp-12_0_0) uS::Socket::freeMessage
0x00007FFC7B32C8DF (FirebaseCppApp-12_0_0) uS::Socket::freeMessage
0x00007FFD79BF1BB2 (ucrtbase) configthreadlocale
0x00007FFD7BBD7344 (KERNEL32) BaseThreadInitThunk
0x00007FFD7BD226B1 (ntdll) RtlUserThreadStart

========== END OF STACKTRACE ===========

A crash has been intercepted by the crash handler. For call stack and other details, see the latest crash report generated in:
 * C:/Users/diego/AppData/Local/Temp/Unity/Editor/Crashes```
static matrix
#

well

#

go to that path

#

C:/Users/diego/AppData/Local/Temp/Unity/Editor/Crashes

#

its eating up a TON of the perf

#

I wish i could see which collider types or which objects had a lot of the calls, since I cant seemingly even with deep profile

fallow quartz
static matrix
#

this is my own issue, nothing to do with you

heady iris
#

do you have a lot of rigidbodies rattling around?

static matrix
#

yes

heady iris
#

contacts are computed for collisions, and collisions are caused by rigidbodies

static matrix
#

let me try removing collision for the dynamicarms
it wasn't working to keep them from going through walls anyways

#

yeah that helped

night kernel
#

Can anyone help me with my player's movement script? My player walking to automatically moves to the right and I want it to automatically move to the left as well with a and d keys. How can I do it?

static matrix
#

rb.velocity = new Vector2(movespeed, rb.velocity.y)
that line is causing it

night kernel
static matrix
#

simple left right script is typically as follows: (in update)

var Horizontal = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(Horizontal*Speed, rb.velocity.y);

this should work for your purposes
to make it better, make horizontal a field of the class , and update rb.velocity in FixedUpdate

night kernel
#

Thank you so much

tulip frigate
shell scarab
#

Hey guys, there’s nothing that could possibly break from scripts that are not CLSCompliant right?

heady iris
#

are you having a problem?

stone knot
#

Hey, I have an app in the Google Play Store.
I have installed Unity Ads, which you can skip after one second. However, the skip button is not there for most adverts, it only appears when you click on the advert once. This is bad because many users think that the adverts cannot be skipped and then have to watch the 30-second-long adverts. That's not good, because I definitely don't want that.

Is there any way to set the button to always appear and not disappear?
If not, I'm thinking about not using Unity Ads any more.

indigo verge
#

I have a weird question, and it's hard to ask because I'm not sure exactly how to word it. Is there a good way to project a mesh onto a 2D surface, to create a polygon which is a silhouette?

I have this thing I want to do, where I take a mesh, and create a pipe with the same profile as the mesh in question, as if they "fit" together.

I've found resources on generating Convex Hulls and Concave Hulls, but they don't seem to be exactly what I'm after.

leaden ice
indigo verge
#

Won't that create an outline which doesn't respect the original mesh, though? Like, if the mesh is of an "X", the result of a convex hull would be a square, as far as I've been able to figure out.

leaden ice
#

yes a convex hull would be

#

A concave hull not necessarily, but concave hulls are tricky

#

If you know the order of the vertices you can create the 2d polygon pretty simply

#

For example if you have your 3D mesh and you number the vertices, then you can create the 2D polygon with the vertices in the numbered order

#

concave hulls are simpler when the vertices have a known order

indigo verge
#

YEah, I'd basically just need a way to find all vertexes that are on the "outline" of the object.

dusk brook
#

I'm creating 50,000 game objects (2D circles, nothing fancy) but my unity is dying. Every performance video talks about gpu instancing or setting game objects as inactive if not visible. I want all 50,000 game objects (preferably more) on the screen at one time. Is this possible and can gpu instancing be applied here?

leaden ice
#

you should not be using GameObjects anymore

#

switch to something like ECS or some hybrid setup with Compute Shaders/RenderMeshInstancedIndirect etc

dusk brook
#

i don't need them to be gameobjects in the slightest, just dots

heady iris
#

well, speaking of dots,

leaden ice
#

hahaha

heady iris
leaden ice
latent latch
#

you can just use gpu instancing if you dont need any specific logic tied to them

heady iris
#

Just switching to manually rendering the circles instead of using tens of thousands of sprite renderers is probably enough

#

You can directly tell the GPU to draw a mesh at many positions

leaden ice
#

I highly recommend everyone learning compute shaders and RenderMeshInstanced as a brain enrichment activity.

heady iris
#

i read about the latter once so i'm basically a subject-matter expert

#

also i watched a friend briefly explain foliage via an mspaint drawing

shell scarab
heady iris
#

I would only expect this to be an issue if you were interfacing with VB or F# or something

#

Unity uses unsigned integers in some places, and those are already non-compliant!

shell scarab
#

i had no idea unsigned integers weren’t CLS Compliant

#

Well itll probably be fine then

heady iris
#

(Well, unsigned chars are ok)

wheat cargo
#

Is it possible to have an editor assembly not get domain reloaded?

leaden ice
wheat cargo
modest ether
#

Hey Ho, can Somebody confirm that AudioSource.PlayScheduled() doest work as expected in WebGL even when the documentation says WebGL supports this API. I just want to be sure before I create a bug report lol 😂

#

Whatever you put into it the AudioSource just immediatly plays without the desired time you put in.

#

its weird because you can get the DSP Time and all

latent latch
#

Audio Mixer stuff I know in general doesnt work with webgl

#

no clue of the actual reasons

modest ether
#

Doesnt have to do with the mixer

latent latch
#

ah, ok looking at this method I'd expect it to work then. Don't think I've touched this one before though.

modest ether
#

You can use it to create Beat Synced Audio Events

#

I already got it working but now in webgl it all falls apart...

#

I thought yeah fine I know that in Webgl stuff like the Audioclip Data isnt that feature rich but well I looked in the docs and worked a way of doing it anyway by just knowing stuff likes samples and frequency in my audio clip

latent latch
#

Honestly, this is something I've should have used in previous projects

modest ether
#

and AudioSource.PlayScheduled() is marked as working in webgl... well yeah it does but it just ignores the time you put in

#

For me it sounds like a bug

latent latch
#

All I can think of is perhaps some clip settings you have enabled

modest ether
#

Just thought I did something wrong... no I just ruled out all thigns

latent latch
#

and it's interfering with the method

modest ether
#

yeah but what

latent latch
#

Unfortunately I'm terrible at audio stuff and is usually the last thing I throw into my projects haha

modest ether
#

one WebGL behaviour is that you cant get the clip.samples when the audioclip is not playing, so you just play the clip muted and you can Access this data for you calculations

heady iris
#

WebGL often has limitations with anything that's supposed to happen asynchronously

#

you know, i'm not sure how audio works at all on that platform

modest ether
#

also like clip.frequency doesnt exist but well you can hard code 41000 as an int 😂

heady iris
#

i guess it's just updated every frame instaed of being a separate thread

#

(actually, it's just that you can't do multi-threaded C#, i think)

modest ether
#

na its definitly not frame by frame

heady iris
#

SPECULATION!

modest ether
#

yeah 😂

#

but seriously it just doesnt work at all

#

its just acts like play

#

which is not what you want

#

WebGL doesnt use FMOD it uses native browser calls

#

So I think I will create a bug report

latent latch
#

I just know I've had sync problems with audio in webgl in the past and never felt the need to correct it

#

usually the comment about the cpu spikes though is handled by the background loading option, no?

#

which itself is some async operation

modest ether
#

what do you mean?

latent latch
#

If you don't enable load from background on your clips, you will usually have some sort of sync problems the first time that clip is played in the scene.

#

Audio is just a lot to load in, so ideally you want to load it all at some loading scene (at the start) of your scene.

modest ether
#

and the playscheduled loads the clip anyway

#

also the function doesnt work with my playsfx on beat stuff

latent latch
#

Right, I'm just saying it's one issue I've had with some desync issues, but I guess the idea of this method is it's still not sync'd enough unless you schedule it in a way.

modest ether
#

I can spam the sfx how many times I want because playscheduled behaves as the time is just 0

#

and the time to next beat variable is perfectly calculating

#

as a double and all

#

just this stupid playscheduled doesnt work as it should 😂

#

heck even my Synced Events work

latent latch
#

Some fps game I've worked on in webgl the bullet sfx is slightly off and it's something I've been meaning to fix and I guess this should be what I probably need to use.

modest ether
#

look at this blog, its a really good starting point

#

but yeah doesnt matter if it doesnt work

heady iris
#

audio is interesting

modest ether
#

yeah

heady iris
#

it's happening way faster than video

#

kilohertz, rather than dozens of frames per second

modest ether
#

thats why there is the AudioSettings.dspTime as a double

#

and you use like the PlayScheduled with the dspTime together

#

for example if I want the audio the be played in exactly 1.2 Seconds I would add the current dsptime together with 1.2 and put it in the PlayScheduled

#

you can use this to stitch together audio sources like an Intro part and a looping part, and then you can calcualate the beats and bars and know exactly when they occur and do stuff with it

#

like play sfx on beat

#

Or like fire animations, tough these have to be on frames again

#

So yeah you can recreate Hifi Rush 😂

#

but not in WebGL I guess 😭

chilly surge
#

For a rhythm game though, you probably don't want to use dsp time, you still need frame time to sync up audio with graphics. But well that's besides the point, if PlayScheduled doesn't work as intended then that basically ruins the whole thing.

modest ether
#

Na thats not necessary, audio to be synced is more important then the visuals, we humans can deal with alot of Audio Visual delay actually so using Events in an Update is fine

raven basalt
#

    IEnumerator LoadSceneCoroutine(string sceneName)
    {
        transition.SetTrigger("Start");

        yield return StartCoroutine(WaitForRealSeconds(transitionTime));

        //yield return new WaitForSeconds(transitionTime);

        SceneManager.LoadScene(sceneName);
    }

    IEnumerator WaitForRealSeconds(float time)
    {
        float elapsedTime = 0f;
        while (elapsedTime < time)
        {
            elapsedTime += Time.unscaledDeltaTime;
            yield return null;
        }
    }

The transition is the animator. I am trying to make the transition use Time.unscaledDeltaTime so that it continues to run even when the game is paused, which is when the timescale is set to 0. However, this doesn't seem to be working.

modest ether
chilly surge
modest ether
#

yeah but the key is more to have the visual part seperated from audio and input

#

If you press on beat then it still counts and the visual follows

raven basalt
modest ether
#

dont use TimeScale 😅

raven basalt
#

I'm not sure how to pause everything in the game except for 1 thing without using timescale

modest ether
#

try using something different then WaitForSeconds

#

a while loop will work

#

you need to create you own timer

spring creek
raven basalt
modest ether
#

TimeScale = 0 stops the Update Routine but not a Couroutine, but WaitForSeconds will stop working

spring creek
modest ether
#

I guess its the same with WaitForRealSeconds

raven basalt
heady iris
#

Update runs once per frame

#

It doesn't matter what the timescale is

heady iris
spring creek
# raven basalt I know what a singleton is

Ok, so that singleton has a bool.

Everything you want to pause checks the state of it.
If the bool is true (game is paused), then return

if (PauseManager.instance.isPaused) return;

modest ether
heady iris
raven basalt
spring creek
modest ether
#

but the point stands WaitForSeconds breaks 😂

heady iris
modest ether
#

or whatever you put into unity

heady iris
#

One important thing, though, is that your animator might be stopped

modest ether
#

I used Fixed Update to get more precise inputs in a 30fps game 🫠

heady iris
#

Consider using Unscaled Time if you want to ignore the timescale

#

oops, that was not a very useful screenshot

raven basalt
spring creek
heady iris
#

this is the inspector for the Animator component

raven basalt
#

I can't find it

naive swallow
spring creek
#

It is unfortunately named, but that is the Animator WINDOW. The component would be on a gameobject, viewed via the inspector window

raven basalt
#

It works now after I adjusted the time scale on the animator. Thanks!

heady iris
#

Interesting. I don’t know it abruptly stopped at zero

#

That’s good to know!

#

Actually, since the number of times it’s called per frame depends on the timescale, that implies it runs 50 times per in-game second

#

That sounds right, since I remember having to adjust fixedDeltaTime to update physics more frequently during slow motion

#

And that also makes sense given that fixedDeltaTime will still be 0.02 (by default) no matter what the timescale is

#

If it ran at 50hz in real time, you’d move too fast in slow motion

golden garnet
#

Hey! Im having issues getting a collider to react to a trigger. No matter what ive done, (adding/removing rigidbodies, messing with collider and rigidbody settings, double-checking tag names and OnTriggerEnter scripts, checking the physics matrix) nothing seems to work. I have other objects in the scene that respond to it so I'm not sure why this one specific object type isn't reacting.

somber nacelle
latent latch
#

both must have colliders, one must have a rigidbody, one must have IsTrigger on the collider

golden garnet
waxen spruce
#

Is there a wrong way to write a command in the command pattern? How complex should a command be on average?

earnest pawn
#

I'm making a tower defense and would like to have a tower that boosts other towers within range. I'm trying to use OnCollisionEnter2D to find when a tower is within range, but this TANKS the framerate, I can only have 1-2 of these towers on screen while staying above 60FPS. Any suggestions?
https://pastebin.com/Qt6QbyT4

#

I have every other tower using Physics2D.CircleCastAll almost every frame to find a target to shoot at and that barely affects framerate at all, but I was having a hard time using that in this situation because those towers only have one target at a time, whereas I want these ones to be able to affect every tower within range

latent latch
#

Dont understand why it would tank. It should only happen once anyway, but you should be using trigger colliders, not collision

#

Ideally, CircleCast the buff towers too every few frames.

#

I think the best way to do it though is have some manager that holds the radius/ranges of buff that when a tower is place it looks up the table of these buff towers and subscribes to them, but that's probably a lot more work.

leaden ice
leaden ice
latent latch
#

oh yeah overlap circle because circlecast can actually miss detection it's at

leaden ice
#

It's just conceptually wrong to use circlecast

earnest pawn
#

Thank you both I will look into this

latent latch
#

I usually use overlap in conjunction with casting if I were to use it

earnest pawn
#

okay well the buffing part of it is working but I still can't figure out why it's tanking the frame rate. I can put down 4 of the ant tower without seeing anything change but 4 of the omniflower and it just destroys the performance. Right now both towers have the same components attached to them. Frame rate is bottom right of the game view

#

The omniflower isn't even doing anything anymore, I have the towers using overlapcircle to find it instead of it using ovelapcircle to find the towers

leaden ice
#

Certainly if you're not using the Non-allocating version that will be part of the problem

jagged snow
#

I'm trying to spawn rows an object that increases by 1 in each row but I need to have them aligned in the middle. It stops so theres something wrong with my formula for getting the X position.

        {
            var spikeRow = CreateRow(_rowMultiplier * i + 1);
            float currentX = -spikeRow.Length * _rowSpacingX; // Find the starting point
            for (int j = 0; j < spikeRow.Length; j++)
            {
                spikeRow[j].transform.position = new Vector3(currentX, 0, i + (i * _rowSpacingZ));
                currentX += spikeRow.Length * _rowSpacingX; // Add Onto the starting point
            }
            yield return new WaitForSeconds(_spikeRowInterval);
        }```
earnest pawn
latent latch
#

id stick some break points on code that should only be executed once

earnest pawn
latent latch
#

I can only imagine you've some exponentially growing logic for each tower placed

#

are you sure you're using OnTriggerEnter and not collision

latent latch
jagged snow
latent latch
#

in that case your space shouldnt increase, only the offset

earnest pawn
#

I had the collider I was using for finding boosting towers also colliding with the dirt objects in the background in the collision matrix so it was generating a bunch of uneeded overlaps. Thank you everyone for the help

jagged snow
latent latch
#

Right, which should just be a constant spacing value

#

only thing changing each row iteration is the offset

jagged snow
#

Struggling a bit atm but does there need to be some kind of check if the row size is an odd or an even number?

winged sphinx
#

how would I export an image of a grid layout of sprites, for the purposes of exporting a deck recipe?

cursive wing
#

i made a simple spider-like entity basics , but when i tried make it stand up with rigidbody's addforceatposition it had this weird bounce and rotationing, how can i make it so it dont do that but still allow rotation?

shell scarab
#

why not just use add force? Add force at position applies torque on the object, which is causing it to spin in your case.

cursive wing
#

I want it to spin based on the environment

#

like if it's falling of a ledge it spin or if it's on a slope it gets more angled

dapper palm
#

how do I make my scene darker and make objects further away less visible?

dapper palm
#

this is what i have but i can still cant figure out how to make farther objects less visible

#

well its the boxs that arent working

leaden ice
#

You need to use 2D lighting

dapper palm
#

oh

leaden ice
#

BTW you need to be using URP for that

dapper palm
#

wheres 2d lighting?

leaden ice
waxen blade
#

I'm looking for opinions or advice.

I have a method spawns objects. It can spawn enemies, items, chests, etc. Currently I have a separate method for each object type, but it's ineffiecient. I would rather have a single method that returns one object type instead of returning an enemy, or an item, or a chest, etc.

Not sure what the best way to go about this. They are all scriptable objects, so I could potentially have all these objects inherit a class called Spawnables, and have Spawnables inherit scriptable object so the objects still get to stay as scriptable objects. But I don't know if it would make sense to have an empty base class that only exists to bundle all the objects together as a single type.

Another option I think is to create a new class that contains every spawnable object as properties, and if the spawn method chooses an enemy, insert the scriptable object into that new class that contains all spawnables and return the new class.

I'm leaning toward the inheritance portion but I don't know if it's right for me to make an empty base class that only exists to tie all the objects together by a single name. What do you guys think?

latent latch
#

What's wrong with having a method for each spawning type? It's less ambiguous, otherwise you're probably doing some comparison somewhere if you're wanting to combine it all.

chilly surge
#

If the spawnable class is just empty, does it really need to exist? It sounds like your method's logic can spawn any SO at that point.

latent latch
#

You could implement spawning logic on the SO itself, assuming it's supposed to be bundle with one specific type. I do this for stuff that I don't usually object pool, but you can probably throw that logic inbetween.

waxen blade
#

The spawns are based on random chance, and in a specific order. So I get a random number, if it's lower than X then an enemy does not spawn. Then I do the same for an item. Then I do the same for a chest. And it keeps going down the path for every other object type. The problem though is I'm introducing another class that needs to spawn something in as well, so I was hoping it could return me a single object type instead of me having to call all those methods.

latent latch
#

ItemSO.Init() -> Returns Item<ItemSO>

waxen blade
#

Maybe nothing is wrong with having a separate method for all of them and I'm trying too hard to optimize, but thought I'd get more insight first.

latent latch
#

If I spawn an enemy usually I am doing calls like

``` because I'm usually object pooling everything
chilly surge
#

It will also help if you can show your current code.

waxen blade
#

Instead of having another class that wants to utilize the spawning logic that goes if (RollForRareEnemy != null) else if (RollForChest != null) else if (RollForPowerup != null) etc. I was hoping to call just one method to get one of these objects.

#

Or maybe not, maybe what I'm thinking doesn't make sense and I should just keep it this way.

left adder
#
    public float walkSpeed = 4f;
    public float maxVelocityChange = 10f;
    private Vector2 input;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();    
    }

    void FixedUpdate(){
        rb.AddForce(CalculateMovement(walkSpeed), ForceMode.VelocityChange);
    }

    void Update()
    {
        input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        input.Normalize();
    }

    Vector3 CalculateMovement(float speed){
        Vector3 targetVelocity = new Vector3(input.x, 0, input.y);
        targetVelocity = transform.TransformDirection(targetVelocity);

        targetVelocity *= speed;
        Vector3 velocity = rb.velocity;

        if (input.magnitude > 0.5f){
            Vector3 velocityChange = targetVelocity - velocity;
            velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
            velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);

            velocityChange.y = 0;

            return (velocityChange);
        }
        else {
            return new Vector3();
        }
    }

Is this considerd a good way of making player movement? first time that i did it my self

latent latch
waxen blade
#

That's a whole 'nother can of worms I'm not ready to discuss. lol

#

But basically a prefab grabs the scriptable object (enemy for example) and uses all of its logic and stats.

latent latch
#

Right, if there's something you did want to minimize, it's using a single prefab type which you build from SOs. That's fine and allows you to reuse them instead of outright destroying.

lean sail
latent latch
#

as for spawning them. It's probably not that big of a deal if you did want to have a central instantiation method somewhere, but you'll eventually be doing some comparisons somewhere in that method.

chilly surge
# waxen blade Here's my code: https://gdl.space/wesipoquwe.cs

Are these the code you want to reuse?

numPadSlot.EnemyData = Instantiate(rareEnemy);
numPadSlot.ObjectType = ObjectType.Enemy;
changeSprite.sprite = numPadSlot.EnemyData.sprite;
if (!string.IsNullOrEmpty(numPadSlot.EnemyData.spawnSound))
{
    AudioManager.Instance.PlaySound(numPadSlot.EnemyData.spawnSound);
}

If so then yes, you can extract them out. They are pretty much all repetitions.

latent latch
#

because you need to know how these SOs are assigned to that object so a type will be needed somewhere.

waxen blade
#

But it's looking like somewhere I'm still going to have to do some kind of comparison like Mao was saying though so I may end up keeping them as separate methods.

chilly surge
#

Are you talking about reusing the Roll* methods, or reusing the repetitive same code of if (rolled != null) { do the spawning } for every type of roll?

waxen blade
#

Both.

latent latch
#

oh yeah you can probably reuse all that if it's not specific only to the enemy.

chilly surge
#

For the latter, you can very much rewrite it as:

EnemyData Roll()
{
    var rareEnemy = RollForRareEnemy();
    if (rareEnemy != null)
        return rareEnemy;

    var chest = RollForChest();
    if (chest != null)
        return chest;

    // ...
}

void Spawn()
{
    var rolled = Roll();
    if (rolled == null)
        return;

    numPadSlot.EnemyData = Instantiate(rolled);
    // rest of the stuffs etc
}
#

Now at least you are not repeating the same spawning logic for every roll method.

latent latch
#

for this:
RareEnemy rareEnemy = RollForRareEnemy();
Do you roll for every type of object you want?

waxen blade
latent latch
#
public enum UnitTypes
{
    Enemy,
    Item,
}

public void Spawn(int digit, UnitTypes unitType)
{

  if (NumPadSlots.TryGetValue(digit, out NumPadSlotData numPadSlot))
  {
      //It also selects the enemy type/appearance
      SpriteRenderer changeSprite = numPadSlot.ObjectSpawnContainer.GetComponent<SpriteRenderer>();
      Unit rolledUnit = RollForUnit(unitType);
  
      if (rolledUnit != null)
      {
          numPadSlot.UnitData = Instantiate(rolledUnit);
          numPadSlot.ObjectType = rolledUnit.GetType();
          changeSprite.sprite = numPadSlot.UnitData.sprite;
          if (!string.IsNullOrEmpty(numPadSlot.UnitData.spawnSound))
          {
              AudioManager.Instance.PlaySound(numPadSlot.UnitData.spawnSound);
          }
      }
  
      //Other logic in a similar fashion
    }
}```
#

one idea

#

Enemy, Item would be derived from Unit. So, you'll eventually have to check for the type which it seems like you do with ObjectType

waxen blade
#

I'll play around with your suggestions. I have to go now, thank you Burrito and Mao!

chilly surge
#

If you have a ton of rolling methods and even writing var x = RollForX(); if (x != null) return x; is getting repetitive, you can further clean it up:

Func<EnemyData>[] _rolls =
{
    RollForRareEnemy,
    RollForChest,
    // ...
};

void Spawn()
{
    EnenmyData rolled = null;

    foreach (var roll in _rolls)
    {
        rolled = roll();
        if (rolled != null)
            break;
    }

    if (rolled == null)
        return;

    numPadSlot.EnemyData = Instantiate(rolled);
    // rest of the stuffs etc
}

Now if you have new things to roll, just add that to _rolls and don't need to touch any of rest of the code.

#

(Presumably your roll methods are quite different from each other that they can't really be made DRYer)

stone knot
#

Hey, I have an app in the Google Play Store.
I have installed Unity Ads, which you can skip after one second. However, the skip button is not there for most adverts, it only appears when you click on the advert once. This is bad because many users think that the adverts cannot be skipped and then have to watch the 30-second-long adverts. That's not good, because I definitely don't want that.

Is there any way to set the button to always visible and not disappear?

maiden heath
#

should i make indivual scripts or just make a HUGE switch statement to control the functionality of my enemies

dusk apex
spring flame
#

I have some weird problem when unity crashes for some reason when I try to add a component to some game object

#

I am working on an editor tool and I add the script in prefab mode, I suspect some reimport magic happens and it crashes unity

#

The worst part is that I can't read anything understandable in the Editor.log

#

Can somebody help me diagnose or tell me how I can debug an editor crash?

#

that's my editor log

spring flame
#

pretty wild, but seems like adding components with mouse click works, but clicking Enter when "Add component" popup with selection is present crashes the editor 🙃

spring flame
#

did it!

#

But idk If I'm simply missing something...

subtle path
#

hey i want to create a scriptable object via the menu (because I have to get rid of the editor code to build)
but whenever I create the scriptable object, it doesnt add its script...

#

When i try to add it manually i get an error.

#
public class FetchColors : Editor
{
    [ColorPalette]
    [Tooltip("This is just to quickly change the actual palette!")]
    public Color Color;

    static ColorPalettes SO;

    [MenuItem("MyTools/FetchColor")]
    public static void FetchColor()
    {
        var lastEntry = Sirenix.OdinInspector.Editor.ColorPaletteManager.Instance.ColorPalettes.Count - 1;
        var colorPalette = Sirenix.OdinInspector.Editor.ColorPaletteManager.Instance.ColorPalettes[lastEntry].Colors;

        SO = (ColorPalettes)CreateInstance(typeof(ColorPalettes));
        SO.Colors = colorPalette.ToArray();
        SO.name = "BrickColor";
        SO.AddComponent<ColorPalettes>();

        AssetDatabase.CreateAsset(SO, $"Assets/ScriptableObjects/{SO.name}.asset");
        AssetDatabase.SaveAssets();

    }
}

[CreateAssetMenu(fileName = ("ColorPalette"), menuName = "SO/ColorPalette")]
public class ColorPalettes : ScriptableObject
{
    public Color[] Colors;
}```
leaden ice
#

Why are you doing AddComponent at all here

#

This is not a component

#

It's a ScriptableObject

#

And you seem to be trying to add itself as a component to itself???

subtle path
leaden ice
#

That's a field

subtle path
#

because i need it to have a script to reference it

leaden ice
#

Huh?

subtle path
#

this object is supposed to be referenced by my runtime component

leaden ice
#

Ok so make a reference to it

#

It's still not a component

subtle path
#

i can reference it as a scriptable object but then i have no access to the color list

quaint rock
#

well is the color list public

subtle path
quaint rock
#

so then you can just access the array from a reference hten

subtle path
#

no i cannot, since the object seems to be created without the script attached

quaint rock
#

recreate the object from the create menu

subtle path
#

i need to delete the addcomponent line for that

heady iris
#

i don't understand your problem

quaint rock
#

its a scriptableobject

leaden ice
#

The type is ColorPalettes @subtle path

#

That's the type you reference it as

#

Because that's what it is

#

Sorry went in a tunnel

quaint rock
#

you never add component it

heady iris
#

you can't add components to scriptable objects, yes

#

they aren't game objects

subtle path
#

but the script that needs that reference, cannot find the colorpalettes script, because its in the editor folder

quaint rock
#

dont put it in the editor folder then

heady iris
#

then don't

leaden ice
subtle path
#

it has to be in the editor folder, because i cant build my project otherwise

quaint rock
#

only put the fetch colors part in the editor folder

#

not the ColorPallet

leaden ice
heady iris
#

we're at Z I think

subtle path
heady iris
#

yes

#

so walk back to the original problem

#

not your attempted solution

#

your attempted solution makes no sense

subtle path
#

i have no better

heady iris
#

Explain your original problem.

leaden ice
heady iris
#

oh hey a typo

leaden ice
#

The problem you're having is trying to include some editor things on a runtime script. This can be done usually with preprocessor directives

#

Or at worst splitting the editor and non editor parts

heady iris
#

yes: you can use #if UNITY_EDITOR to cut out the part that should not be included in the built game

heady iris
heady iris
#

you have only explained your attempted solution

subtle path
#

im not refusing, you are just overloading me with solution suggestions, i dont even had the time lol

quaint rock
#

also if you do the #IF UNITY_EDITOR thing you need to do the same for editor using statements

heady iris
#

if you don't have any time to explain your problem, we don't have any time to help you with it

subtle path
#

if you could chill at least a minute, i could think about how to explain this problem

subtle path
devout silo
#

Hi, I have 2 locations on the screen and I want to stretch a square between them, which will actually be between one location and the other. how can i do that?

wooden pawn
#

So i have this method for grabbing an item that uses scriptable objects to do it. In another script, the method is called by getting the scriptable objects name, value, and a type. however, i want to just get the scriptable object itself and then use the method to pull those values out instead of having to do it in the other script to make it easier and more reusable. how do I check what type of scriptable object something is in the overloads?

public void GetItem(string name, float value, string type)
{

    Debug.Log("Attempted to grab item: " + name + "\n" + "With attached value: " + value);
        if (type == "Weapon")
        {
            weaponsDict.Add(name, value);
        } 
    else if(type == "Accessory")
        {
            accessoriesDict.Add(name, value);
        }
}
safe dirge
#

wouldn't something like type is ScriptableObjectName so work?

wooden pawn
#

i want it to be the scriptable object itself, so i can pull values from it

#

id assume it means i have to make overloads of the scriptableobjects themselves, like i have 3 right now, "Weapons", "Accessories" and "Chest" so id have to do something like
public void GetItem(Weapons weapon, Accessories accessory, Chest chest)

#

but is there any way I can make them optional, so i can put in just one overload?

#

so i dont have to make the other ones null every time

#

when i call it i mean

#

If i was opening a chest, id call it like GetItem(null, null, chestObject) with that

safe dirge
#

you could have a base ItemScriptableObject and then have WeaponScriptableObject : ItemScriptableObject, then have the method take in ItemScriptableObject and have a switch statement for the different types?

wooden pawn
#

that makes sense, but im not so great with encapsulation yet as i just learned it

#

ill see if i can figure it out later

safe dirge
#

You can also use interfaces with this, define some method GetItem in the interface and have your scriptable object inherit from it, then have your sciptable object implement it for each type

silent tapir
#

Should I use a tween/lerp for my ADS or an animation? There will be multiple guns btw.

silent tapir
#

to which one

spring creek
#

You didn't ask which one. Putting or between the choices would have made it a question of which

#

Either works

silent tapir
#

Yeah I did, I said Should I use a tween/lerp for my ADS OR an animation?

devout silo
#

How can I convert a location on the canvas to a real world location?

spring creek
#

Do either

#

Your choice

#

Both work

silent tapir
#

okay

spring creek
#

I read it as asking if you should use a tween/lerp for ads
And also asking if you should for animation.
Apologies for my confusion

astral nexus
#

Hey! I know this question could be answered in different ways based on a person, but how can I setup SCALABLE interaction with objects in terms of architecture?
I'm following "unity way" with more decoupled components as it's core + general good practices in my project, but I'm stuck with interaction system, because I can't decide how to do it more "properly" and scalable
Like, I've tried component based approach and inheritance tree, but I didn't like it and it's quite a mess for something that is just not "fire and forget" interaction (like doors or pickups)
So, how to do it in a "pro way"? Can someone share a good example of that system or just point me in the right direction?

solid timber
#

Im currently making a script to spawn ores randomly on my terrain but it keeps spawing it bellow the terrain how would I get it to "snap" to the top layer? This is the segment im guessing neededs to be edited. Vector3 GetRandomTerrainPosition()
{
// Initialize combined bounds
Bounds combinedBounds = new Bounds();

    // Calculate combined bounds of all terrain tiles
    foreach (Terrain terrain in terrainTiles)
    {
        combinedBounds.Encapsulate(new Bounds(terrain.transform.position, terrain.terrainData.size));
    }

    // Generate random position within the combined bounds
    Vector3 randomPosition = new Vector3(
        Random.Range(combinedBounds.min.x, combinedBounds.max.x),
        0f,
        Random.Range(combinedBounds.min.z, combinedBounds.max.z)
    );

    // Get the terrain height at the random position
    float terrainHeight = 0f;
    foreach (Terrain terrain in terrainTiles)
    {
        if (terrain.terrainData.bounds.Contains(randomPosition))
        {
            terrainHeight = terrain.SampleHeight(randomPosition + terrain.transform.position);
            break;
        }
    }

    // Set the spawn position to the sampled terrain height
    Vector3 spawnPosition = new Vector3(randomPosition.x, terrainHeight, randomPosition.z);

    return spawnPosition;
}

}

#

Thanks you!

waxen blade
#

@solid timber !code

tawny elkBOT
solid timber
#

Im currently making a script to spawn ores randomly on my terrain but it keeps spawning it bellow the terrain how would I get it to "snap" to the top layer? Above is the code segment I beilve is causing the problem. Thank you for any help!

vagrant agate
#

like where below the terrain do you see it spawning

solid timber
#

Its all at one layer im guessing its the 0 layer on the y axis

#

can you send screen shots here?

tranquil shell
heady iris
#

(and the interface part is optional, too)

#

my design is all composition-based

#

At one point I had an interface for two similar components. I wound up factoring out common behaviors into other components, merging the two original components, and discarding the interface thinksmart

#

I do use interfaces a fair bit for non-Component types, though

tranquil shell
#

The way I learned to do things is start with a behemoth script, and only abstract out logic when it becomes obvious that it's useful. Though this is only meant for gameplay scripts. I usually always do audio, animation, and UI in scripts that I can delete and the game will still run fine.

heady iris
#

actually...no, you need to do neither!

#

its input is in world space

heady iris
#

except I wound up going so far with the behemoth component that I got mad and did a complete rewrite

heady iris
#

that'll help you tell if it's working or not

heady iris
true sphinx
#

gameManager.SwitchState(gameManager.SumoState);
I'm currently using this code to make my game manager switch state to the "gameManager.SumoState". I would also like it to switch to other states like "gameManager.LobbyState", or something else that starts with "gameManager.". Is there a way to use a variable by name or similar so i can just put a variable after "gameManager." and it will use that variable?

true sphinx
#

no, dont think so

heady iris
#

Accessing fields by name would be reflection

#

and that usually means you're doing something wrong

true sphinx
#

yea i wouldn't be suprised :/

heady iris
#

Presumably there's a reason you aren't just writing gameManager.FooState or gameManager.BarState

true sphinx
#

yea, i'd like that state to be chosen earlier

#

and have it stored in a variable

heady iris
#

you can put the state itself into a variable

#

unless gameManager.SumoState is constantly changing

#

in that case, if you have a fixed set of possible states, I'd create an enum type and give gameManager a GetState method

true sphinx
#

ah okay, that makes sense

heady iris
#
public enum StateKind {
  Sumo,
  Foo
}

// ...

public State GetState(StateKind kind) => kind switch {
  StateKind.Sumo => sumoState,
  StateKind.Foo => PickCorrectFooState()
};
#

maybe like that

#

i used a function at the end to show that you could have more complex logic

#

this is a switch expression. very handy for picking between things based on an enum value!

true sphinx
#

ah perfect, i haven't used an enum before so this is great, thankyou

heady iris
#

i use it when i'm writing code in discord :p

#

indentation is annoying enough as-is

vivid halo
#

That's fair enough

livid olive
#

I'm having trouble matching heirarchal transform positions. If i place a game object directly in my scene, and place an independent game object within my scene. Will these match or will i require an overall parent to match transformation positions?

heady iris
#

if you give them the same world position, then they'll be in the same place

true sphinx
heady iris
#

If they have the same parent, then giving them the same local position will also put them in the same place

heady iris
vivid halo
#

You can set the position of one object to another in code. You can also ensure an object follows another object by making it child to it.

heady iris
#

as an overload if you sometimes need to let other classes pick a state directly, or as the only option if GameManager is the only one that can pick states

#

the former might look like

public void SwitchState(StateKind kind) => SwitchState(GetState(kind));
public void SwitchState(GameState state) {
  // whatever logic goes on in here
}
#

and the latter would be near-identical; you'd just make the second method private

livid olive
#

i hope the images are ok to post here.

heady iris
#

the camera holder is in the same position as the player

#

that tells you very little about the camera's position

livid olive
#

Oh. Setting local position to zero matches its parents position correct?

heady iris
#

Yes.

#

or does CameraHolder have no children?

#

ah, it does

livid olive
#

Camera holder does

heady iris
#

i presume the camera is one of them

livid olive
fading oracle
#

Hi! A player sent a bug report in my game that they accidently shut down the power while playing, and after booting back up, the keyboard and mouse were unresponsive.

#

How do I begin to diagnose this, does Unity generate error log files somewhere?

#

Well, actually, I know there's this log file. I'm tempted to start by asking them to share that, does that make sense? Or is there something else I'm not aware of?

somber nacelle
#

yeah that's basically the only log file unity will create on the client device. other than crash reports, but if it wasn't an actual crash then there won't be one of those

fading oracle
#

I'm hopeful Unity's Input system throws some errors logs there at start-up

#

but idk

#

Okey, so that's the one. Thank you!

soft shard
#

Im looking for some ideas on how to handle "surface contact" (ex: walking on or having a bullet impact metal, wood, etc, an object falling/hitting that surface, etc) - my first idea was to use a raycast to check the texture or material name, but that feels like it wont scale well for my use case - my second idea was to use a SO that holds a list of materials that should produce specific sounds, though im worried this will also be difficult to manage with more content, any ideas on alternative approaches I could look into or does the SO approach maybe make the most sense for my use case?

tough rampart
#

Okay, I'm not sure where to place this question, so I'll just place it here.
Are there any other developers that are using EditorGUILayout.EnumFlagsField with very inconsistent results whenever it's being used multiple times for the same Enum type? (not variable!)

If you would like to answer this, please Reply to this message or @ me.

Thank you! ❤️

_Ref: https://docs.unity3d.com/ScriptReference/EditorGUI.EnumFlagsField.html_

#

To clarify it a bit more, whenever I'm converting it to a Unity supported type, like an integer, I'm receiving incorrect results.
I'm using Unity 2022.3.16f1

UPDATE: I'm gonna try to reproduce it in an entirely clean project and if it's still happening, I'll report it as a bug.

#

Yeah. It's a bug. I'm gonna report it, lol.

fleet tide
#

Hey !

How can i do an reference specific to the gameobject "player" who we control and not another player ?

the gameobject spawn so i can't do a simple reference and i can't link the script

@gray mural Maybe you know ?

somber nacelle
#

don't ping people into your questions, but there are many ways to get a reference to that object

fleet tide
somber nacelle
delicate forge
#

why is my transform.rotation.eulerAngles.z returning only 0

#

okay, correction: I have a child reference so it's childTransform.eulerAngles.z

leaden ice
delicate forge
#

so then how do i read the z rotation value

late lion
heady iris
#

yes, you can get very surprising results

#

like a slight rotation completely changing all three euler angles

delicate forge
#

yeah i noticed that

heady iris
#

The Z axis should be the best behaved, at least, since the Euler angles represent rotations around your Z, then X, then Y axes

lean sail
delicate forge
#

I'm trying to make a door swing open. I thought i could just coroutines but it has no idea when to stop since it cant read the angle

#

so i guess i'd just have to get the angle through trig, right?

heady iris
#

I'd add two Quaternion fields: one for the closed state, one for the open state

#

You can then use Quaternion.Slerp to move between the two

#
float t = 0;

while (t < 1) {
  t = Mathf.MoveTowards(t, 1, Time.deltaTime);
  transform.rotation = Quaternion.Slerp(closed, open, t);
  yield return null;
}
#

an example

#

this takes one second to open the door

#

or, if you want to use local rotation

#
transform.locationRotation = ...
#

You can right click the rotation in the inspector and hit "copy as quaternion", then paste that into the closed/open fields

delicate forge
#

ohh

#

okay yeah that makes sense

#

i was initially using slerp but I think I was just doing it wrong

#

thank you very much though

heady iris
#

If you want to adjust the motion of the door, you can throw in an AnimationCurve

#
float remapped = curve.Evaluate(t);
transform.localRotation = Quaternion.Slerp(closed, open, remapped);
#

could be handy for making it dramatically swing open

lean sail
#

You might be able to just use an animation too

delicate forge
#

yeah but i figured I'd have more customization via script

atomic sinew
dusk apex
#

You'd at the very least get a complete shape between iterations.

#
for(int i = 0; i < _lineRenderer.positionCount; ++i)
    _lineRenderer.SetPosition(i, _vertices[0]);```
#

It looks like you've got a single point in the middle but I'm assuming you've got every point in the middle prior to setting the point position.

atomic sinew
dusk apex
#

Show your updated code

#

Reminder that changes will not take effect until after you've saved the script.

atomic sinew
dusk apex
#

Well.. the position of vertex zero before being assigned is at (0, 0)

#

So assigning (0, 0) to each position at (0, 0) would make little difference.

atomic sinew
#

right, i put it after the other for loop now :D

#

now it behaves differently

dusk apex
#

You'd want to assign it after establishing the first - aye.

atomic sinew
#

the origin vector shows up at the second segment

dusk apex
#

Not sure what's going on but if it's set to index 0 of the vertices array, all points should start at the first position

#

You could probably skip the first position in the coroutine unless you're wanting to wait for it to move to it's default position.

atomic sinew
dusk apex
#

Could probably terminate one position sooner to remove the last behavior - the final point is already at the initial point.

atomic sinew
dusk apex
atomic sinew
#

it looks kinda ok, but i'd still prefer for it to be simply "drawn"

#

i still don't understand where this "extra line" is coming from

dusk apex
#

Then have all points set to the target point in the second coroutine

dusk apex
#

But now you've got every position at the original point (vertex 0) so every other position after the ith point would be at vertex 0's placement.

#

If you're wanting to make an illusion of adding entirely new points, you could set every point from the current to the end to be at the latest point.

#
    private IEnumerator DrawLineSegment(Vector3 start, Vector3 end, float duration, int endIndex)
    {
        float timer = 0f;

        while (timer < duration)
        {
            timer += Time.deltaTime;
            Vector3 newPosition = Vector3.Lerp(start, end, timer / duration);
            
            for(int i = endIndex; i < _lineRenderer.positionCount; ++i)
                _lineRenderer.SetPosition(i, newPosition);
            yield return null;
        }

        for(int i = endIndex; i < _lineRenderer.positionCount; ++i)
            _lineRenderer.SetPosition(i, end);
    }```
#

Programming on mobile discord, expect mistakes.

atomic sinew
#

very impressive - I'll have to stare at that code for a bit

#

is there some sort of karma system here or something?

dusk apex
#

Nope, everything's voluntary. Glad everything's working 👍

atomic sinew
dusk apex
# atomic sinew It's a pretty neat script now. I put it here in case you wanna use it: https://h...

A minor refactor/optimization would be to use SetPositions (plural) rather than SetPosition (single).
Set Position: https://docs.unity3d.com/ScriptReference/LineRenderer.SetPosition.html

Consider using SetPositions instead, if setting multiple positions, as it is much faster than making individual function calls for each position.
Set Positions: https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
This method is preferred to SetPosition when setting all positions, as it is more efficient to set all positions using a single command than to set each position individually.
You'd cache all of the changes and set the positions in a single batch - added a cache for the line renderer (an array) and modified the set position lines to not immediately make changes to the line renderer but to only do so after all positions/changes have been set https://hatebin.com/jjdhgnirvb

rancid frost
#

similar to how you can combine mesh and draw them in draw call,
can thesame be done for sprites, while maintaining sprite individuality? or while I just need ALOT of sprites renderers when putting many sprites on a map

frosty coral
#

so i have my code and for some reason i want the bullethole effect to not show when im in my reload animation. i have been following a tutorial and when this problem occured i have been searching for a solution for days. when i have my reload animation playing and i click the bullethole effect shows and i dont want that. https://pastebin.com/xjSFJCTD

dusk apex
dusk apex
#

So they're objects that are instantiated in the scene?

frosty coral
dusk apex
#

And you don't want them visible when reloading?

frosty coral
#

yes

dusk apex
#

Cache every bullet hole instantiated and simply set their renderer component to not be enabled when reloading.

frosty coral
#

the prefabs have this. i dont see a render component

dusk apex
#

Scroll down just to be sure?

frosty coral
#

ok

dusk apex
frosty coral
#

wait do i put these somewhere in my code? ParticleSystem.Play(), ParticleSystem.Stop()

#

ohhh

dusk apex
#

You could pause them as well if you don't necessarily want to stop em.

frosty coral
#

ok alright

#

ill try to figure out how to do that

frosty coral
dusk apex
# frosty coral i tried. i dont know what im doing ive never done this before

Cache the bullet holes:```cs
private List<ParticleSystem> bulletHoles = new List<ParticleSystem>();
[SerializeField] private ParticleSystem bulletHoleGraphic;//No point in referencing it simply as a GameObjectcs var bulletHole = Instantiate(bulletHoleGraphic, rayHit.point, Quaternion.FromToRotation(Vector3.forward, rayHit.normal)); bulletHoles.Add(bulletHole);cs
private void Reload()
{
reloading = true;
shooting = false;

    // Play reload animation
    if (gunAnimator != null)
    {
        gunAnimator.SetTrigger("Reload");
    }

    Invoke("ReloadFinished", reloadTime);
    foreach(var bulletHole in bulletHoles)
    {
        if(bulletHole)
        {
            bulletHole.Stop();
        }
    }
}``````cs
private void ReloadFinished()
{
    bulletsLeft = magazineSize;
    reloading = false;
    foreach(var bulletHole in bulletHoles)
    {
        if(bulletHole)
        {
            bulletHole.Play();
        }
    }
}```This would stop the particles when reloading and play them again after finishing the reload.
frosty coral
#

oh ok ty

frosty coral
dusk apex
frosty coral
#

oh ok 6 errors though but i will fix them. if i got some questions i may ask later on

frosty coral
dusk apex
frosty coral
#

ohhhh

dusk apex
#

You should be able to right click List and add the namespace.

dusk apex
arctic steeple
#

If a component class is addresed, then the object that was created from that class can affect the component attached to the target game object ?

#

I'm sorry im dumb and new at unity ;_;

dusk apex
#

I just didn't catch what you were trying to ask/verify.

#

I'm assuming you're suggestion something related to if an object is referenced.. (it could be a prefab or scene object)

arctic steeple
#

If I have the myRigidbody object created from the class Rigidbody2d, then I can use it to change the Rigidbody2d component in the Unity window ?

frosty coral
#

what does this even mean

dusk apex
# frosty coral what does this even mean

That means you've got two bullet hole graphics variable in your class. Likely your original GameObject reference and the new Particle System reference I posted above. Where they were meant to be the same reference.

frosty coral
#

oh thats not good

#

i delete one i guess

rough scaffold
#

what are "objects" in terms of being an "instance of a class"
and i can use "new" to make a new instance of a class?

dusk apex
#

Calling the public methods on that instance would make changes apply to that instance.

#

So if you've referenced the bird in the scene with that script (both components should be in the scene - don't reference the prefab unless you're just wanting to spawn the bird) you would be able to modify it's velocity via Rigidbody2D - it must have a Rigidbody2D to be referenced properly (the Inspector will not allow you to reference an object without that component and through code will just have you reference null if the object does not have said component).

frosty coral
#

my solution that i tried did not work. i dont mean to be rude by interupting _V's help

dusk apex
dusk apex
#

You might want to ensure that your IDE is properly configured if it isn't yet.

frosty coral
#

oh ok

frosty coral
#

!IDE

tawny elkBOT
dusk apex
frosty coral
#

do i delete the reds

dusk apex
#

You'd just remove the bullet hole graphics variable/field on line 27.

frosty coral
#

like this?

dusk apex
#

I chose to reference that same object as a Particle System to reduce unnecessary GetComponent calls.

frosty coral
#

oh ok

dusk apex
#

General rule of thumb is that you shouldn't ever have to reference a particular object as GameObject unless you're really not needing it for anything other than what GameObject can do - you can always access the GameObject using a component's gameObject property.

frosty coral
#

uh something happend

dusk apex
frosty coral
#

yes

#

theres no place to assign in the inspector

dusk apex
#

[SerializeField] attribute would show private fields in the inspector - private prevents other classes from easily tampering with them.

dusk apex
#

You'd make it public if you're wanting other classes to modify the field - relative to explicitness.

frosty coral
#

tbh bro i dont know how to code

dusk apex
#

The above would make it show up in the inspector.

#

Reminder that you've got a type mis-match in the inspector as well - drag and drop the wanted object into the field.

frosty coral
#

ok

#

i got the muzzle flash assigned but it isnt showing

dusk apex
frosty coral
dusk apex
frosty coral
#

yes

dusk apex
#

Did you save?

frosty coral
#

yes

dusk apex
#

Are all errors fixed?

frosty coral
#

yes

dusk apex
#

Show the current code

frosty coral
#

whats happening

dusk apex
#

Booting up my Unity and verifying if Particle System is visible to the inspector.

frosty coral
#

oh ok for some reason my messages wernt allowed for a second

#

i sent an image of my code and it was red

#

the whole message was

dusk apex
#

Likely bot spam protection (too many messages or the messages were too small)

frosty coral
#

oh ok

dusk apex
#

It should be visible cs public class WhoAmI : MonoBehaviour { [SerializeField] ParticleSystem ps; }

frosty coral
#

where do i put that code

#

oh nvm

dusk apex
frosty coral
#

theres no field for that

dusk apex
#

Maybe you've got console errors.

frosty coral
#

yep

dusk apex
#

The component will not be updated if you've got errors.

#

Clear the errors.

#

Did you save the script?

frosty coral
#

oml the field changed positions. i couldnt see it ;|

#

mb

dusk apex
#

Make sure you've assigned that and muzzle flash

frosty coral
#

its still happening when i click while reloading

#

i did for the muzzle and its still not showing

dusk apex
frosty coral
#

the ammo counter goes down aswell

dusk apex
#

Are there any errors?

frosty coral
#

yeah

#

let me check

#

nope

dusk apex
#

So do the particles stop and start again when reloading?

frosty coral
#

ima send a video rq

dusk apex
#

Something to be concerned about

frosty coral
#

no way bro. i thought that meant how long it took the animation to play

#

it works

#

i feel so dumb

dusk apex
#

You've got instant reload

#

Rapid fire

latent latch
#

bzzt

frosty coral
#

the muzzleflash still wont show

latent latch
#

you got that rendering on the gun camera?

frosty coral
#

yes the pixel art

latent latch
#

or are you using 1 camera

frosty coral
#

two cameras, one for the gun to not clip through stuff and one for the pixel art and main surroundings

latent latch
#

so the muzzle would be on the gun camera

#

so make sure it's not culling it

frosty coral
#

oh ok

frosty coral
latent latch
#

It's up to preference to how secondary rendering like post processing should affect it. More advance stuff such as changing rendering ordering is also useful for stuff like that.

frosty coral
latent latch
#

Oh, you're just rendering a texture here, ah

frosty coral
#

kinda

latent latch
#

But the particle system should still render if you don't cull the layer

frosty coral
#

do i put it on the same layer as the gun or the same layer as the enviroment

latent latch
#

currently you've got it set to weapon

frosty coral
#

yes

latent latch
#

you need to include the particle system layer onto it too

frosty coral
#

oh

#

so i have to write a new code for the weaponcamera to have the muzzleflash particle?

latent latch
#

No, stick the particle system on the same gameobject as the weapon, or if it's on its own gameobject then the layer needs to be not culled by the camera

#

So, make a layer called something like MuzzleFlash and add it to the culling mask

frosty coral
#

on the gun? mb that i dont know anything

latent latch
#

The particle system gameobject

#

im not sure how you're instantiating it so it depends how you are

frosty coral
#

ok

latent latch
frosty coral
#

ok

old sigil
#

would anyone know of a way to use Resources.Load<Sprite>() to grab an individual sprite out of a spritesheet?

#

im trying to use the name of the individual sprite in the sheet thats sliced but it wont load it

leaden solstice
#

If you are using addressable assets they get subasset name and you can access directly

#

Other way is getting SpriteAtlas then using GetSprite

gray mural
hexed pecan
#

Find is the least preferred way. That page has other suggestions

#

I would probably store the main player in a singleton when instantiating it

somber vortex
#

Hi - i'm trying to rotate rigidbodies smoothly. I've been using rigidbody.moveRotation but it snaps to the rotation in one fixed time step. I need to be able to rotate from current rotation to a new set rotation gradually. What's the easiest way to do this?

latent latch
#

If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MoveRotation will resulting in a smooth transition between the two rotations in any intermediate frames rendered. This should be used if you want to continuously rotate a rigidbody in each FixedUpdate.

#

Go over the docs one more time, otherwise post code

somber vortex
#

I followed the documentation exactly. How do I post code? Just paste it?

#

rotMovementDirection = new Vector3(speedAdjXVelocity, 0, speedAdjZVelocity);
if (rotMovementDirection != Vector3.zero) newTransformRotation = Quaternion.LookRotation(rotMovementDirection, Vector3.up);
rotationVelocity = new Vector3(0, 10, 0);
deltaRotation = Quaternion.Euler(rotationVelocity * Time.fixedDeltaTime);
rigidbody.MoveRotation(newTransformRotation * deltaRotation);

#

this just snaps it in one fixed time step to the "newTransformRotation". I need it to move gradually to the newTransformRotation

vestal arch
#

the interpolation is set on the rigidbody in the inspector, try checking that

somber vortex
#

yeah interpolation is on

#

I had it working by setting transform.rotation but it messes up the physics if I use transform.rotation so I need to use a rigidbody function but be able to move from my current known quaternion to a new known quaternion gradually (i.e. not snapping the movement in one fixed time step)

latent latch
#

post the full code

#

!code

tawny elkBOT
unkempt lintel
#

this methods being called in OnInspectorGUI but it's causing a great deal of lag the more notes there are. any ideas for how I would optimize it

{
    if (notes.arraySize > 0)
    {
        for (int i = 0; i < notes.arraySize; i++)
        {
            SerializedProperty subProp = notes.GetArrayElementAtIndex(i).FindPropertyRelative("subdivision");
            SerializedProperty posProp = notes.GetArrayElementAtIndex(i).FindPropertyRelative("subdivisionPosition");

            if (subProp.enumValueIndex == subPos.x && posProp.intValue == subPos.y)
            {
                return true;
            }
        }
    }
    return false;
}```
hexed pecan
unkempt lintel
#

is it possible to cache these serializedproperties somehow

hexed pecan
#

@somber vortex probably easiest to store your angles in floats and interpolate those (Mathf.MoveTowardsAngle). Then make a quaternion out of those floats (Quaternion.Euler).

latent latch
#

well, you're getting back the serialized values each update. You can possibly limit to how much you're refreshing the UI with these new serialized values

unkempt lintel
#

so FindPropertyRelative is definitely the most expensive thing there right

#

been trying to narrow it down as much as i can

hexed pecan
unkempt lintel
#

not much exp with custom editor

latent latch
unkempt lintel
#

good point

latent latch
#

only thing I can think of those is just don't update the values if the object your are modifying isn't the active element

#

probably some ways to gauge it

#

no clue why those calls would fps drop you though as you're just doing a single index lookup

#

with a define path /shrug

unkempt lintel
#

the weird thing is it almost feels like a memory leak. it gets slower and slower as i move my mouse around

#

which makes me think the serializedproperties arent being disposed, so i tried disposing them manually, but no luck

somber vortex
#

thanks guys will try these suggestions

lament sequoia
#
void Update()
{
    if (isMoving)
    {
        moveCounter += Time.deltaTime;
        float t = moveCounter / moveDuration;
        t = Mathf.Clamp01(t);
        t = 1f - (1f - t) * (1f - t);

        this.gameObject.transform.position = Vector2.Lerp(moveStartPos, moveEndPos, t);

        if (t >= 1f)
        {
            isMoving = false;
        }
    }
}

public void CloseGame()
{
    Application.Quit();
}

public void MoveIn()
{
    if (!isMoving)
    {
        moveStartPos = this.gameObject.transform.position;
        moveEndPos = moveStartPos;
        moveEndPos.x = moveStartPos.x - 2000f;
        moveCounter = 0f;
        isMoving = true;
    }
}
```Im firing the MoveIn() by using it as a button .onClick() event listener, i want to make a gameObject's X position move 2000 to the side but whenever i fire the MoveIn method the gameobject X position goes to -216000
#

Any idea why its not lerping it to 2000 but to -216000 instead?

#

Btw moveDuration is a float with a value of 2

unkempt lintel
lament sequoia
#

Yeah

#

Also the gameObject has a rectTransform instead of a normal one

#

Im not sure if this has anything to do with it

unkempt lintel
#

OH yeah recttransforms are weird im pretty sure

#

one sec

#

lemme find where i did this

#

try localPosition

#

instead of position

#

this is what i did in my thing whereim moving recttransforms
element.localPosition = Vector3.Lerp(element.localPosition, toTarget.localPosition, t);

lament sequoia
#

Yuppp that worked

#

Thanks man ive been stuck on this for a while xD

#

RectTransforms surely are weird

unkempt lintel
#

indeed

fleet tide
gray mural
fleet tide
gray mural
#

As this has something to do with the other players

nova leaf
#

can someone help me please with my code (regarding rotation), i just can't get it working i feel so useless ._.

unkempt lintel
#

yeah ask it and someone may be able to help

nova leaf
unkempt lintel
#

that makes sense. you should describe the problem then prompt ppl to go to ur dms

#

cuz someone might say theyre down to help but be unfamiliar with the topic

leaden ice
nova leaf
#

just trying to make a turret that's on the sides/top/bottom of a spaceship, which i want to rotate with the ship ofc, but rotate towards the target to shoot it (turret has 2 parts, one rotating only on y and one only on x) but i can't get it to work even tho it's simple i guess

leaden ice
#

Convert the world space position of the target into the coordinate space of the the turret mount.
Then project that local space position onto the desired plane
Then rotate the turret towards the projected position

lament sequoia
#
public void SetCharacters(string Char)
{
  Debug.Log(Char)
}
```Is this the right way to use the Button component OnClick event listeners?
#

For some reason it doesnt print out the string fencer

nova leaf
leaden ice
lament sequoia
#

Yeah

leaden ice
#

Seems correct...

#

You sure there's no errors anywhere?

#

And you sure that's the correct script?

#

And you sure you saved your code?

lament sequoia
#

Ill share the correct script to see if it helps explain the issue

#

But its basically what i posted

leaden ice
#

Can you show a screenshot of your console window?

#

After clicking the button

#

The full window

unkempt lintel
#

LOL i know what ur looking for

#

ive done it too many times

leaden ice
#

Mhmm pretty common

lament sequoia
#
public void SetCharacters(string Char)
{
    GameObject clickedButton = gameObject;
    GameObject equippedImage = clickedButton.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject;

    if (UnitsSelected.Contains(Char))
    {
        equippedImage.SetActive(false);
        UnitsSelected.Remove(Char);
    }
    else if (UnitsSelected.Count < maxUnits)
    {
        foreach (string i in UnitsSelected)
        {
            Console.WriteLine(i);
        }

        equippedImage.SetActive(true);
        UnitsSelected.Add(Char);
    }
}
#

The Console.WriteLine(i); isnt printing anything

leaden ice
#

Why are you using console.writeline in unity

#

Debog.Log is what you want

lament sequoia
#

The first answer i got was to use this

#

Ill try debuglog

leaden ice
#

Answer from where lol

#

Someone who doesn't know Unity

#

Anyway there's like 3 conditions that need to be true for that code to run

#

So It's very possible it's not running

leaden ice
lament sequoia
#

Ive been debbuging most of the code

#

And the only issue i could find was that the parameter wasnt passing anything

unkempt lintel
leaden ice
#

With Console.WriteLine?

lament sequoia
#

No i was only using console log for the list

leaden ice
#

Yeah why lmao

lament sequoia
#

Debuglog for any other simple debugging

#

Like i said, someone told me to

leaden ice
#

You need to add more logs

#

Check all these conditions

#

Check the length of the list

#

Etc

#

Debug.Log only, no Console

dusk apex
lament sequoia
#

Yeah seems like the parameters are passing fine

#

Im trying to deactivate/activate an image with that code

#

But the image doesnt change at all so im guessing equippedImage reference is the wrong stuff

unkempt lintel
#

im having trouble understanding the conditional

lament sequoia
#

Its a character selection screen

#

When the player picks the difficulty, it sets a maximum amount of characters it can select(maxUnits)

#

And when it selects a character, its supposed to add it to the list of selected characters only if theres enough space

#

Theres also an image that activates and deactivates to make it clear if the character is selected or not

#

But the image doesnt change

#

I think it may be the way i reference the image

unkempt lintel
#

its hard to look at new code and understand it, but is weapons not being cleared when u unselect the weapons

#

it clears on Awake

lament sequoia
#

I just tried debugging and it seems like its referencing gameObject to the gameObject of the script instead of the button gameObject

unkempt lintel
#

GameObject clickedButton = gameObject;

#

its setting it to the object this script is on

lament sequoia
#

ChatGPT recommended this for me some time ago

unkempt lintel
#

ya its assuming the script's on thebutton

lament sequoia
#

Ohhhhhh

unkempt lintel
#

gameObject will always return THIS object

#

thats why u dont need to write "this.gameObject"

sharp juniper
#
    {
        notebook = GameObject.FindGameObjectWithTag("Notebook").GetComponent<Notebook>();
        GetComponent<Button>().onClick.AddListener(() => notebook.SelectClue(GetComponent<CombineNotes>()));
    }``` I have this piece of code of a piece of text that is instantiated during playtine and I need to give its button an event. For some reason it never does this though and it has everything necessary there. Does time.timescale make a difference
#

No it doesn't

#

just tested it

#

it has everything connected but just can't make the button

nova leaf
# leaden ice Convert the world space position of the target into the coordinate space of the ...

so i tried to do this

Vector3 direction = target.position - turretBase.position;
Vector3 localDirection = turretBase.InverseTransformDirection(direction);
localDirection.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(localDirection);
turretBase.localRotation = Quaternion.RotateTowards(turretBase.localRotation, targetRotation, horizontalRotationSpeed * Time.deltaTime);

i don't understand InverseTransformDirection, because if i rotate the turret it looks in the right direction but not at the target

leaden ice
nova leaf
#

what

leaden ice
#

There should be two objects

#

The base

#

And the turret itself

#

The turret should be a child of the base

nova leaf
#

the base is the part that rotates horizontally and the barrel i add later vertical

leaden ice
#

You need a third object then

nova leaf
#

for what

#

they both are a child

leaden ice
#

A base, the horizontal rotating part, and the vertical rotating part

nova leaf
#

of the turret itself

#

i do

#

but the turret parent itself is not rotated in code

leaden ice
#

Ok then the turret itself needs to be what you're calling inverse transform point on

leaden ice
nova leaf
#

the parent is the object the script is on

#

so"transform.rotation"

#

what am i supposed to change now

#

i am trying to make this shit work for so long now pls just end my suffering

gray mural
nova leaf
#

but i want it to rotate with the spaceship the turret is on

#

and still rotate towards the enemy

#

(also, only on one axis)

gray mural
nova leaf
#

i don't know what that means

gray mural
#

Have you gone to school?

nova leaf
#

yes atwhatcost

gray mural
#

That's the formula you need

nova leaf
#

no

gray mural
nova leaf
#

pls just end me

#

make it stop

gray mural
#

I have provided the formula for you, and now you start whining for... not writing the full code for you?

#

Perhaps, I also should send you a full .unitypackage file with the solved issue?

nova leaf
#

Get down off your high horse megamind
i am so sorry my adhd brain can't learn that shit and i know from experience i shouldn't even try. and it not being in my main language makes it even harder.
i am not dumb, i already have a game with multiplayer and mod support and i just asked what i have to change in my code to fix it. and a formula doesn't help me personally ._.

swift falcon
#
{
    public abstract void StartSkill(Unit user, List<Unit> targets);
    public abstract void FinishUse(Unit user, List<Unit> targets);
    public abstract void TriggerChannel(Unit user, List<Unit> targets);
    public abstract void End(Unit user, List<Unit> targets);

    public abstract string GetSkillDescription(Unit user);

    public SkillData Data;
}```
i have this abstract SO Skill class with a SkillData class with basic stuff like skill name, cooldown, cost, etc
inheriting and overriding the base functions lets me have good control of how a skill functions

my problem with this is each Skill is just referencing the SO, if i wanted to change something in SkillData like the cooldown, it would change the base SO
what's a way i can tackle this?
unkempt lintel
#

arent scriptableobjects kinda like abstract classes themselves

#

wouldnt u just make instances of a Skill

swift falcon
#

you mean with ScriptableObject.CreateInstance()?

dusk apex
unkempt lintel
#

unless u need to make them at runtime

swift falcon
#

i do make them like that and it works well until i want to modify its properties at runtime

lean sail
swift falcon
unkempt lintel
#

i would say try removing abstract? i dont see why u need them unless im not understanding something

#

couldnt it just be a scriptableobject

lean sail
#

No, by just storing the relevant fields needed

lean sail
swift falcon
unkempt lintel
#

ohhh gotcha

swift falcon
#

not entirely sure what you mean

lean sail
#

Im not sure what else to say to explain it, it's just
SkillData myData;
And you copy it from the SO

swift falcon
#

that sounds doable yes, the problem is i would lose some flexibility with having each Skill have unique values that aren't in SkillData

lean sail
#

You don't have access to those values anyways if all you ever reference is this Skill class

swift falcon
#

i do within the derived classes, but i see your point

#

i'll try that out

#

ty

swift falcon
#

skill.Data = new(skill.Data); constructor to copy the data
skill.Data.cooldown.BaseValue = 1; changing value of data
seems to still modify the SO

leaden ice
#

they are references

#

so your copy is referring to the same instance of them

#

depending on how your constructor works

swift falcon
#

oh big true

#
{
    ...
    this.stats = new(skillData.stats);
}```
still the same issue 🤔
#

do i need a Stat constructor that copies a Stat?

leaden ice
#

what does new () do on the constructor for it?

swift falcon
#

skillData.stats is a list of the Stat class, new there just does the default constructor for lists

#

oh wait

#

you mean the SkillData constructor

leaden ice
#

List of WHAT

swift falcon
#
{
    ...
    this.stats = new(skillData.stats);
}```
leaden ice
#

oh is stats a list

swift falcon
#

yeah

leaden ice
#

ok so yeah I mean

#

what is Stat

#

if you're just making a new list referring to the same Stat objects

#

then you still have a problem

#

you'll want to create a new copy of each stat

#

Assuming Stat is a class

swift falcon
#

yea big true ty working on that now

gray mural
swift falcon
#

never thought about it really, haven't used structs much, it's just value vs reference right? i do need to reference stats a bunch, would i still be able to do that with it as a struct?

leaden ice
#

You wouldn't be able to reference one and have it affect the original in the list

#

it depends if you need that ability or not

#

Using structs would save you from having to write copy constructors etc though

#

and has the potential to be more efficient.

So it really depends on what you're doing

swift falcon
#

i do need to reference them unless there's other ways to make changes to them that doesn't involve references

leaden ice
#

in effect a "pseudo-reference" consisting of a reference to the list and the index in the list.

swift falcon
#

i could possibly do that

#
{
    baseValue = _stat.baseValue;
    ...
}

public SkillData(SkillData skillData)
{
    this.stats = new(skillData.stats);
    ...
}```
this is still modifying the SO
leaden ice
#

so like:

foreach (var oldStat in oldList) newList.Add(new Stat(oldStat));```
swift falcon
#

gotcha

leaden ice
#

One question though

#

baseValue = _stat.baseValue;

#

is baseValue float?

#

Or some class?

swift falcon
#

double

leaden ice
#

ok that's fine then

#

as long as none of the fields inside Stat are classes then you're good

swift falcon
#

👍

#

do i put the copying constructor in the class itself or a util class?

leaden ice
#

Could be either one, but if it's in the class itself you get access to private variables

#

Usually it'd be in the class itself

swift falcon
#

right right

#

will new use the list constructor automatically or do i have to call it somehow?

heady iris
#

It's a target-typed new

#

It'll call a constructor for the type on the left hand side of the assignment, in this case

#

so yes, it'll construct a list here

static matrix
#

this may be a monumentally stupid question but is it possible to make strings editable like TMPro data
Like with the big edit box

heady iris
#

Yeah, use [TextArea]