#archived-code-general

1 messages · Page 359 of 1

mellow sigil
#

You can't have both rigidbody physics and character controller at the same time. You have to pick one

sterile reef
#

alright chat, ive been looking into Unity event systems but after seeing what it does im not sure if its fits my situation

so, i have a player entity. that entity can perform stuff. so what i (would) want is a system that has Events (like onHurt, OnRun, OnAttackHit, Etc)
how would i go about doing this

#

my initial thought was having a central Event Monobehaviour with all the On* events. then in other classes (like movementcontroller, healthcomp, weapon classes) whenever the [moveclass] detects when you press shift, it would also signal OnRun in this case

#

then i can make components that subscribe to these events, which in turn execute specialized code

#

so, the ultimate question, is this the right way to do it?

#

are my thought going in the right direction or not

leaden ice
#

UnityEvent if you want to set up the subscription in the inspector

#

Otherwise, regular C# events will do

#

I don't see a reason for a "central" event behavior

#

The movement system would fire the movement events, and so on

#

Keep it simple

sterile reef
#

so instead of putting these Events in a central class i put the movement related events in the movement class

#

got it

static pollen
cosmic rain
narrow sphinx
glad dew
#

Unity events are pretty bad for maintenance. Can't refactor easily, can't find references to events in code. It's basically a crude tool for giving gamedesigners on your team a crappy form of visual programming with no safeguards.

cold parrot
long hare
#

What theme are you using ?

weak spruce
knotty sun
#

or the script is just not running

simple ridge
#

Hi all, I was wondering if anyone knew if their was a way to speed up gizmo rendering. I'm writing some really quick prototyping code that just displays the colour of cells in an area (currently 50, 50) this is fine but I want to expand this further and have a larger area displayed. At the moment though it is already noticably laggy in the inspector is their a more optimal way of doing this (that isn't printing to a texture or something simular as this is meant to be a quick prototype that I am repeatidly changing)

#

I'm currently using Grizmos.DrawMesh and passing in a Quad, are handles more optimal for these things?

leaden ice
crimson talon
#

does anyone know why it does this and how to fix it?

#

ends up breaking the whole project then having to restart from scratch

simple ridge
#

The colour of the mesh is determined by certain states of the grid, so its just meant to visualise different data

#

So the way I'm currently doing this is just using a switch statement to set colour based on different states and then rendering at a given coord the mesh

leaden ice
burnt rivet
#

anyone here used mixamo ?

simple ridge
rigid island
spring creek
tawny elkBOT
simple ridge
#

Is their any better documentations with examples of the outputs for these noises and their ranges / limitations?

gusty aurora
#

WTF is the range of a noise function ?

simple void
#

that depends on your noise function

gusty aurora
#

Are you talking about the period of the noise ?

simple void
#

Usually Classical Noise will be -1->1 as well as simplex noise

mellow sigil
#

Mathf.PerlinNoise is "infinite" (the entire float range)

simple ridge
simple ridge
mellow sigil
#

Perlin noise generates the same value for all integer inputs. That's probably throwing you off.

simple ridge
#

Hmm, let me check. I am 90% sure that the values I am passing it should be going up in a 0.05f step but I may have messed something up

simple ridge
#

Ahh, yeah your right. My bad. Sorry Dx
I was sampling the position but not adding the 0.05 offset so it was taking the integer position each time.

onyx cypress
spring creek
weak spruce
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

strange gust
#

Hello everyone. Idk if this is the right channel to ask, but i have a question regarding my current setup and ways i might be able to improve the current workings or completely revise how it works.

Right now i have a building system which consists of cubes. Cubes can be attached to eachother which makes them act as one object (by being children of the same rb parent) as well as detach from eachother and seperate the attached cubes if necessary.

Currently i handle detachment by storing what is attached on each cubes face and using a bfs algorithm to traverse the cube structure and check what is attached to what after removing a certain cube, though when doing this it might cause a significant lag spike depending on how large the structure is. Any way i can improve on this or another way to handle this?

Placement manager (calls attach and detach methods): https://gdl.space/lopafotajo.cs

BlockManager (handles the attachment and detachment): https://gdl.space/baqezopeya.cs

somber tapir
#

Is there a way to make this work from the base class?

leaden ice
jovial valley
#

_> Code ASMR just popped up (all of the semicolons lined up perfectly)

spring creek
#

That is pretty nice. My compulsion would make me put the two TMP_Texts and two GameObjects together

leaden ice
gusty aurora
#

Also the other components are probably on that gameobject

fossil blaze
#

How to make a 3 sec hold button?
with a radiant progress bar

bright maple
#

Quick hiccup I'm dealing with here: I have a series of health bars and other informational gameobjects tagged as "DEBUG" for a script to let me activate and deactivate them. The script is completely detached from anything that is tagged, and I double checked that the bools in the script are acting as needed. The issue is that for some reason GameObject.SetActive(false); works just fine, but GameObject.SetActive(true); does not.

leaden ice
bright maple
#

yes and the bools are switching just fine

#

Deactivating them works just fine, but when I press the button again, they don't reactivate. Once again, the script isn't attached to anything that is tagged.

modern creek
rigid island
bright maple
rigid island
bright maple
#

not yet, I only just now considered that

modern creek
#

😛

#

I mean, to be fair, that's gotten me in the past too

rigid island
modern creek
#

that one little word "active" hiding in there 🙂

bright maple
#

omg that is really embarassing

#

Well thanks for the help!

modern creek
#

s'ok, honest, I think it's kind of a gotcha about unity

rigid island
#

FindObjectsOfType can return inactive objects if you specify so

spare island
#

is there a way to prevent a setactive?

#

I want to intercept a setactive call to keep the object active for an animation before setting it to inactive

prime vapor
#

Hi Unity friends.
I'm meeting a conundrum that I feel like there should be an easy solution to but can't figure out the right call.
I have a game with AI that follows/ attacks the player. There are some gameplay elements that dynamically cause zones to get temporarily covered in fire. I want AI to avoid walking in theses zones if possible. The player has access to a kick and can kick (physics) the AI into the fire zones.
My first solution was to use nav mesh obstacles. That way the AI correctly avoided the fire zones. However, since nav mesh obstacles CARVE the navmesh, enemies kicked into it instantly teleport back to the nav mesh.
I've heard that unreal has stuff like a "weight" logic where you can add "weight" to parts of the navmesh so that NPCs TRY to avoid these zones but still know how to navigate if they're in it. Anyone know if there is a similar solution (or a different one) to this issue?

spare island
prime vapor
#

I know about those but, dynamically?
Can't navmesh volumes (to setup areas) only be used when baking?

spare island
#

outdated manual oops

spare island
prime vapor
#

Alright, thank you!

modest sun
#

Hi! Fellow Unity Users, How are you all doing? this is the first time i use Unity 3D and i am still learning so i am currently stuck without knowing how to code.

tawny elkBOT
#

:teacher: Unity Learn ↗

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

spare island
#

There is also visual scripting

modest sun
#

visual scripting

spare island
#

..yep?

modest sun
#

visual scripting is for what?

#

Like coding?

spare island
#

yes

spare island
modest sun
#

And is visual scripting hard?

spare island
#

its maybe easier to understand at first than normal coding

#

its about the same difficulty overall though since you're doing the same things

#

also most tutorials will not use visual scripting

modest sun
#

But it's easy to learn it then.

proven jasper
#

I would say the difficulty ramps up substantially given the general lack of documentation and poor support

spare island
#

exactly ^

proven jasper
spare island
#

its easy to start but learning anything in depth will be difficult

proven jasper
#

Which practically, not really.

spare island
#

i dont know anyone who uses visual scripting in unity other for things like dialogue or behavior trees

proven jasper
#

You need to wrap your heads around the same concepts, but in a format basically no one uses

spare island
#

not for writing all code

proven jasper
#

Without the advantage of years of free educational resources focusing on C#

spare island
#

i actually might try to use visual scripting for my UI stuff

#

easier than making a million little code scripts for each button

proven jasper
modest sun
#

It's either visual scripting or C# one of them has to be excluded.

spare island
#

idk nobody else ever complains about it but working with unity UI is super slow

#

im guessing thats what UI toolkit is for, havent tried it yet

proven jasper
rigid island
#

visual graphs look like shite

proven jasper
#

Visual scripting is a gimmick to get people to switch over from RPGMaker and Gamemaker

spare island
#

imo its to compete with unreal

#

blueprints too good

proven jasper
#

Unreal blueprints are a lot more tightly integrated

spare island
#

and faster

rigid island
#

still looks like shit

spare island
#

so does C++ code imo

proven jasper
#

Header files atwhatcost

rigid island
#

yes i rather look at the graph in that case then deal with C++

proven jasper
#

The few times I had to deal with it I just used UnrealCLR

#

But unitys approach to a lot of, well stuff, is just much more open ended and imo more intuitive

spare island
#

man i could already be done writing the script by now

#

i guess its not even good for that (edit: i think this may just be the first time you use it?)

modern creek
#

Why can't I add a mesh collider on a parent (and then link the child gameobject with the mesh)

rigid island
#

the mesh itself not the component

modern creek
#

yeah, won't let me .. It's NBD, just for organizational reasons, but it appears as if the mesh collider has to be on the same object as the mesh renderer

rigid island
#

it doesnt

#

make sure you're dragging a Mesh inside not the MeshRenderer or anything

modern creek
#

ooooooooh, that's what i did

rigid island
#

click the mesh filter on the child, it leads to you to the mesh then use that instead

modern creek
#

already generated the MR from the M

#

perfect, thanks

modest sun
#

How to create a single game just like the Blood 2 The Chosen game series?

#

Was it 2D or 3D?

#

The original game.

spring creek
rigid island
#

chosen was 3D (lots of hours spent on this game :P)

#

blood1 - original was 2d

spring creek
#

Ah yeah, i just read the blurb

The original Blood won numerous fans, despite the fact that it was a 2D shooter released nearly a year after Quake made 3D environments standard.

#

Please don't send a google link that takes up my entire screen

#

Glad you found something. No need to actually post it here...
Was just trying to show that you can actually access Google yourself to look. Not really a question for here

rigid island
#

also this is a code channel @modest sun

modest sun
spring creek
modern creek
#

Any tips for debugging raycasts & cinemachine? I have a bit of code that seems like it ought to work.. but doesn't:

        private HexPoint _lastMouseOver = HexPoint.None;
        // private int terrainLayer = LayerMask.NameToLayer("Terrain");

        private void CheckForMouseOver()
        {
            v($"Mouseposition is {Input.mousePosition}");
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            HexPoint targetHp = HexPoint.None;

            if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
            {
                Transform targetTransform = hit.transform;
                TerrainHex target = targetTransform.GetComponent<TerrainHex>();
                // snip validation shit here
                targetHp = target.Location;
            }
            if (targetHp != _lastMouseOver)
            {
                v($"Location of mouse changed to {targetHp}.");
                _lastMouseOver = targetHp;
            }
        }
modest sun
spring creek
# modest sun Where to post it?

Nowhere. Why post it? You were the one with the question. You found the answer. Done
Good work on getting the correct answer

modest sun
spring creek
#

I mean, sure, I could probably figure it out. But could I explain it to you here? Not really

modest sun
spring creek
#

Have you made games before? If so, you should understand why

modest sun
spring creek
tawny elkBOT
#

:teacher: Unity Learn ↗

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

oblique spoke
rigid island
modern creek
#

Yeah.. Just curious how? I'm a bit newer to 3d work. I am tinkering with Debug.DrawRay() but I'm not seeming to see anything.. Spitting out numbers to the console seems like.. it should be working, but it's a bit hard to visualize

rigid island
#

yeah you dont even need those anymore

#

pullup the Physics Debugger under Windw => Analysis

modern creek
#

OK, lemme try that

rigid island
modern creek
#

Hm. OK, I must be doing something wrong.. Disabled everything and nothing disappeared. 😛

oblique spoke
rigid island
#

make sure you have gizmos enabled in scene view

modern creek
#

That's NP - I'm just having a bit of trouble understanding why the raycast is failing.. it does look right

#

Yeah, I just turned those on and saw a flash of a red line - debug.drawray - but then it went offscreen in my cinemachine pan..

#

I'll try the query, sec

#

Ok, one problem is that I was using Camera.main and that doesn't give me the "blended" camera for cinemachine while easing between two vcams, but I don't know the solution for that

#

The other is that I must not have the right components for Physics.Raycast to return a result on my component. What components do I need? I only have a MeshCollider at the moment (or maybe I'm not wanting to use Physics.Raycast?)

#

Ah, yeah, I need a RB on it.

lean sail
crude mortar
#

not sure exactly what you are saying here but there is no "blended" camera, it's just interpolating the main camera's position / rotation from one vcam to another, it's not creating some new camera with its own position / rotation just for the blend

modern creek
lean sail
#

Do you know which line its specifically wrong at? Like is it not detecting the object at all

modern creek
#

So here's the level - I'm currently doing "DrawRay" from Camera.main to the raycast from Camera.main to mouseposition.. If you look, the red line gets shorter and short until it's a point at the conclusion of the blend

#

I gotta make a quick call but I'll brb

crude mortar
#

also, you should look at this scene from the scene view, not the game view, otherwise the line will always look weird since its coming from the exact center of the camera

modern creek
#

Ahh, that might be it

#

I was doing NameToLayer (in Awake() )

modern creek
lean sail
#

i just put the game and scene view side by side

crude mortar
#

hmm I have my unity layout set up so I can have the scene view and the game view open at the same time so that there is no reason to pause

modern creek
#

hm.. I changed the layer mask but maybe I'm doing this wrong.. I'll have to google

#
        private int terrainLayer;

        private void Awake()
        {
            terrainLayer = LayerMask.GetMask("Terrain");
        }
        private void CheckForMouseOver()
        {
            // ... 
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            HexPoint targetHp = HexPoint.None;

            if (Physics.Raycast(ray, out hit, 100f, terrainLayer)) { ... }
        }
#

I just need the mask of the layer I'm looking for, I assume

#

like a bitmask

crude mortar
#

I would change the type to LayerMask, although I am actually not sure if it matters?

#

(talking about the terrainLayer variable)

modern creek
#

I could do that - I just memoized it because it seemed bad to do in every frame

#

maybe that's a problem, too, losing somethign important in the implicit cast

#

oh, no, GetMask returns an int

crude mortar
#

I dont mean cast it every frame I mean just change the type.. doesnt the overload take a LayerMask? or is it doing a cast in the function call

#

ah okay then

#

guess it makes sense

#

do your colliders actually exist and function properly? it looks like a custom mesh

#

what type of collider are you using?

modern creek
#

mesh collider

#

so the raycast is definitely.. working as I want it to, I'm just not getting the target in Physics.Raycast

crude mortar
#

I would just log what I was hitting then..

modern creek
crude mortar
#

Oh, it's not hitting

modern creek
#

That's what I mean - nothing's getting hit at all.. Physics.Raycast returns no items

crude mortar
#

your message confused me

#

but okay yes can you just spawn a cube and give it a rigidbody, and have it properly collide?

modern creek
#

sure, lemme try

crude mortar
#

(and im sure you have quadruple-checked your layers are correct on the cell objects)

modern creek
#

I'm pretty sure.. I have this in the init for the cells:

        public void Initialize(HexPoint p)
        {
            int terrainLayer = LayerMask.NameToLayer("Terrain");
            if (gameObject.layer != terrainLayer)
            {
                w($"Hex {p} does not contain the Terrain layer and will not function properly with raycasts. This is a bug.");
            }
#

(and it spammed up the console - as I expected - until I set the layer properly on all the prefabs)

lean sail
#

as a sanity check, can you also show the code with the draw ray lines.
when i have raycast troubles ill normally just try it on a cube first

modern creek
#
        private void CheckForMouseOver()
        {
            v($"Mouseposition is {Input.mousePosition}");
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            HexPoint targetHp = HexPoint.None;

            if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
            {
                d("Ding!");
                Transform targetTransform = hit.transform;
                TerrainHex target = targetTransform.GetComponent<TerrainHex>();
                if (target == null)
                {
                    w($"Raycast hit something ({targetTransform.gameObject.name}) that wasn't a TerrainHex. This is a bug.");
                    return;
                }
                targetHp = target.Location;
            }
            if (targetHp != _lastMouseOver)
            {
                v($"Location of mouse changed to {targetHp}.");
                _lastMouseOver = targetHp;
            }
            v($"Cam position is {Camera.main.transform.position}, ray direction is {ray.direction}");
            Debug.DrawRay(Camera.main.transform.position, ray.direction * 100000f, Color.red);
        }
#

here's everything, unedited

#

_lastMouseOver is just memoizing the last hit hex - my plan is to show a "highlight" hex as you mouse over, but I didn't want to be doing it every frame for every hex, so I'll just emit an event when it changes

crude mortar
#

I am confused by this, what is the drawray meant to tell you then? are you determining its not hitting using of your target == null check?

modern creek
#

"ding" never happens, ever

crude mortar
#

ah

#

okay so then yes, I would make sure the mesh collider is actually generating properly

modern creek
#

ok so raycasts work on the cube.. so something must be broken on my mesh collider

lean sail
#
  if (Physics.Raycast(ray, out hit, 100f, terrainLayer))
  {
            Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.green);
  }
  else
  {
              Debug.DrawRay(ray.origin, ray.direction * 100f, Color.green);
  }

doesnt fix the issue but i would use draw ray like this

modern creek
#

do those layers (include) need to be set on the ~~render ~~ meshcollider?

crude mortar
#

render collider?

modern creek
#

sorry

#

mesh collider

crude mortar
#

no, they dont

modern creek
#

could it be somethign with the normals on the mesh itself?

#

I didn't generate the mesh

lean sail
#

hm does it need to be convex?

modern creek
#

also - "convex" isn't checked, does it need to be?

crude mortar
#

I dont think it would, as you can definitely raycast against objects in your level like a house or something, which have a mesh collider (I mean as a general use case of raycasting)

modern creek
#

It is a convex mesh, I suppose I'll enable it? (not sure why it needs to be, seems like it's an optimization for properly normalized meshes?)

crude mortar
#

just for funzies, I would enable "queries hit backfaces" in the physics settings of your project

#

and see what happens

#

but its possible it failed to generate the collider entirely

#

because of some weird non-manifold geometry issue

modern creek
#

in the mesh - does "generate colliders" need to be checked?

crude mortar
#

I dont believe so either, none of my models have it checked and the mesh collider works

#

but you could try the convex option on the mesh collider, although its less of a fix and more of a bandaid

#

(assuming it works)

modern creek
#

ah! something worked

#

either me enabling convex or me enabling backfaces

#

lemme turn one/other off

lean sail
#

maybe the normals of the faces were pointing in weird directions, if enabling backface worked

modern creek
#

Yeah, it works now that I've enabled convex on the mesh collider

#

weird that it didn't before!

crude mortar
#

well, you could just roll with that then lol, but yes very strange

#

I wonder why

modern creek
#

I'm imagining that this mesh has f'd up normals? maybe it's even inside out?

#

I didn't generate this mesh but don't know how to check

lean sail
#

i could take a look if you dont mind, though im no blender expert i dabble

crude mortar
#

it would render weird if it was inside out though, so I am not sure

modern creek
#

sure, have at it, sec

#

Thanks for the help both y'all

crude mortar
#

seems pretty simple / normal to me, however I am not sure how the mesh collider handles scenarios with open faces like this

#

so maybe it just decided it couldnt do it and didnt generate a collider

#

although I wouldn't exactly expect that to be honest

modern creek
#

oh, it doesn't have a bottom?

crude mortar
#

yeah

lean sail
#

yea this looks a bit off

modern creek
#

maybe the collider needs 2 hits to be a collision? ie, one on the front face and one on the back face?

#

I bet that's why setting it to convex worked - it only looks for one collision on an "outside" face

crude mortar
#

convex does fix this issue though (I mean conceptually, it would fill in that gap) so seems like a good solution for this

#

yeah exactly

#

something like that

modern creek
#

weird one, well, TIL

lean sail
# modern creek weird one, well, TIL

could also try filling in the face, if you select the whole edge loop with (alt left click) then press F it should be fine as is. Although not sure if thats truly gonna fix it, thats how you would make it a complete shape

modern creek
#

In unity?

#

I don't have blender, or any skills to use it 😛

crude mortar
#

its more ideal to not have an extra render face that you will never see so its fine

#

convex works

modern creek
#

It's no problem to use the convex solution - it's actually probably an inadvertent optimization

#

But I'll probably long term want a bottom to these hexes.. in case there's any sort of physics stuff with the hexes going flying or whatever

lean sail
#

right now, you should see through them if looking from below

oblique spoke
modern creek
crude mortar
#

victory

lean sail
modern creek
#

Awesome, thanks!

lean sail
#

i also dont know what export settings was used when it was created, i noticed this object isnt centered and was slightly rotated lol

#

rotated by 0.0009

modern creek
#

Wanna do a couple hundred more? 😛 3x3, 6x6, and so on 🙂

crude mortar
#

"this isn't what I signed up for"

modern creek
#

Good to know on the rotation .. I don't think it'd matter? But it might be visible along the edges/corners

#

In fact...... lemme look closely

crude mortar
#

it was probably just floating-point error on the import to blender, or the export from blender in the first place

modern creek
#

nah they look fine to me, even under scrutiny

crude mortar
#

yes its a very small decimal so not noticeable

modern creek
#

they're just temporary assets anyway.. we're still sorta worldbuilding

lean sail
#

oh sorry it wasnt 0.0009, it was -0.000009

modern creek
#

haha

#

yeah that's probably fine

#

(although I am the kind of person who will type 0 into the rect transform values over and over until they settle on 0)

#

Ah darn, memefree zone. 🙂

#

Anyway, you know what I'm talkin about. Feels good man.

#

😛

queen saffron
#

Hello, is there an asset or package can assist with GameObject vertices/edges/faces selection process? My aim is to manipulate elements position

#

Hope converting a mesh to triangles meshes that each one contain a unique collider is not an option xD

leaden ice
queen saffron
#

I've been trying to use that ElementSelecion but it didn't go well (bugged for me)

#

Like imagine having a game object on a scene and you aim to modify its vertices or faces with translation operator

#

I want to let the user to manually select vertices / faces or edges if possible and apply necessary changes

leaden ice
green cradle
#

Hello! I am VERY new to unity and programming in general but I was wondering if anyone had a fix for this? It is probably something simple i am doing wrong

Basically i want to hold the wand and have it collide with objects, i set the default XR grab interactable on it with "velocity tracking" movement type and it seems very jittery as seen. Do yall know how to fix this and still have it collide with objects? pictures of the settings following

#

lemme know if this belongs in another channel

green cradle
#

Since i dont plan on using alot of grabable objects, a possible solution (more of a workaround) ive been thinking of is to have a solid body that looks like hands follow the hand position instead, making the controller hands themselves invisible. the solid objects would get stuck on the geometry if it follows using velocity and i could switch out the models using area triggers (ex: pick up want here! and when the selector is activated in the designated area the rigid body would swap out for a hand holding a wand instead). The wand wouldn't be throwable though which isnt an issue for me
This solution seems very performance intensive though to constantly have a rigid body track the hands. and its still using the underlyig principle of velocity tracking which doesnt seem to be working out well for me right now

broken light
#

how do you change material data in edit mode on a per object basis? since you can't use .material since it warns about leak when not in play mode. but using sharedMaterial effects all objects

#

kind've damned it you do, damned if you dont

mighty void
#

Anyone have a méthod or Know a méthod to make a sphère based on cubes? Like Minecraft? In coding i mean

broken light
#

find the width or height either one then the sphere is the position and the radius is half the width or height

#

oh wait you mean to voxelise a sphere?

#

a flood fill will be the simplest way based on the sphere bounds then remove any cube that is not within the radius distance

leaden ice
broken light
#

since i only really need it at run time but need to test it in editor

green cradle
# green cradle

im sure its a simple fix, i just dont know what setting i have wrong XD

raven orbit
#

do any of you suggest a project? I’m a beginner and I’d like to expand my knowledge on object oriented programming

cosmic rain
#

OOP can be applied to any project, so pick whatever you're interested in.

cloud carbon
#

is anyone here?

#

PLEASE HELP It has been 2 days. I can't make this work!!

Question
Hello. I am making a hyper-casual game in Unity. I am currently working on the gates that have numbers like “x2” or “+50k” or “-7k”. I assume you already know how these gates work. But the problem is… For some reason, the variables are working as static. If I assign the gate script to one gate. It works perfectly without any problems. But if I make 2 gates & assign the same script to the 2 gates. Both gates do only one modification.
Example: First gate is set to +500. Second gate is set to -600. If I play the game and collide with the first gate. I get +500. But if I collide with the second gate. I still get +500. But… I am supposed to get -600.
Thats the problem. This is my script. Please help me. For the love of god, end this 2 days of suffering!!

tawny elkBOT
mossy snow
cloud carbon
#

please help T-T

lean sail
# cloud carbon look at these 2 vids

most people really arent gonna watch long videos to attempt to debug your issue. you should debug to see whats happening. you cant just start the problem with "i assume you know what gates are"

cloud carbon
#

dude. you can look at the vid for 3 secs and you will understand what the gates mean

lean sail
#

🤷‍♂️ im just telling you the truth, people wont help when the first link i click has a 3 minute video and it seems you made 0 effort to debug

mossy snow
# cloud carbon please help T-T

what debugging have you done? what happens if you set a breakpoint in OnTriggerEnter? Why didn't you rename your GameObjects properly? Did you try disabling one of the gates? If you had these two videos already (which ideally would have been screenshots), why did I have to drag that info out of you?

cloud carbon
#

Someone in reddit asked for a vid recording so i thought you guys might ask abt it too

knotty sun
cloud carbon
cloud carbon
knotty sun
cloud carbon
#

Forget this. I found the solution.

#

The collider wasnt moving with the hand

#

2 days wasted

raven basalt
#

In blender, I made a non humanoid armature with an ik bone. When I import it to unity, when I try to move the ik bone towards the player through a script, the rest of the armature doesn't follow along with the ik bone. How do I go about fixing this?

hasty wave
#

why would the color utlity have an error? it works on my other scripts?

wintry crescent
#

through the "out color" part, it sets the variable color to the output

knotty sun
wintry crescent
#

but it itself, doesn't return anything

wintry crescent
knotty sun
#

tbh, that whole statement makes very little sense

simple egret
#

The statement is a ternary expression so it does make sense to use it like that
Though only ColorUtility is underlined, so maybe you have your own class named that, so there's an ambiguity between yours and Unity's?

knotty sun
simple egret
#

It's valid though

knotty sun
#

I did not say it was not valid

simple egret
#

It works, yes it assigns twice but it does the thing as intended

#

default(Color) might not be black so the ternary acts as a default value assignment

#

It's a short for

Color col;
if (!ColorUtility.TryParseHtmlString("", out col))
    col = Color.black;
knotty sun
#

Actually it is not, it is short for

Color col;
if (ColorUtility.TryParseHtmlString("", out col))
    col = col;
else
    col = Color.black;

which you would never write

simple egret
#

You know that out acts like ref right? So your snippet is execution-wise strictly identical to mine
The compiler might even elide the unnecessary assignment to itself

knotty sun
#

the simple solurion is

Color col = Color.black;
ColorUtility.TryParseHtmlString("", out col);
simple egret
#

Nope, as you need to assign all the out variables in a method before returning it will overwrite it with some default value (which might not be black), even if the method returns false

knotty sun
simple egret
#

Hah weird, I expected transparent (RGBA all to 0)

knotty sun
maiden junco
#

I'm having issues teleporting the player to a specific position, I'm using the StarterAssets Third Person Controller unity package.

ThirdPersonController.cs: https://pastebin.com/WGnskBWY
GameManager.cs:


using UnityEngine;
using StarterAssets;
public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }
    public Room currentRoom;
    public Room startingRoom;
    GameObject playerFollowCamera;
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void Start()
    {
        playerFollowCamera = GameObject.FindWithTag("PlayerFollowCamera");
        SetRoom(startingRoom);
    }
    private void UpdateCameraBounds()
    {
        CustomConfiner confiner = playerFollowCamera.GetComponent<CustomConfiner>();
        CameraBoundsCollider bounds = currentRoom.GetComponentInChildren<CameraBoundsCollider>();
        Debug.Log(bounds.transform.GetComponent<Collider>());
        confiner.m_BoundingVolume = bounds.transform.GetComponent<Collider>();
    }
    public void SetRoom(Room newRoom)
    {
        currentRoom = newRoom;
        ThirdPersonController.Instance.transform.position = currentRoom.spawnPoint.position;
        UpdateCameraBounds();
    }
    public void ChangeRoom(Room newRoom)
    {
        // Get the door that has as destination the current room
        Door[] doors = currentRoom.transform.GetComponentsInChildren<Door>();

        foreach (var door in doors)
        {
            if (door.destination == currentRoom)
            {
                ThirdPersonController.Instance.transform.position = door.destination.spawnPoint.position;
                break;
            }
        }

        currentRoom = newRoom;
        UpdateCameraBounds();
        Debug.Log("You are now in " + currentRoom.name + ". " + currentRoom.description);
    }
}

pseudo kiln
#

Just doing a quick glance it looks like your if statement is checking if door.destination matches the room you're currently in and not the room you want to teleport to?

#

I hesitate to speak authoritatively on that though, it's just something that caught my eye that I wasn't sure was intentional

maiden junco
#

Oh sorry for not having stated it out, I'm making a room system, where I can move through doors, and it basically should teleport the player to the new room spawn point

#

But that doesn't happen

#

The UpdateCameraBounds works

#

And in general the teleport system works, but the ThirdPersonController is not being teleported

#

I even tried to disable the Char Controller while doing the position change but nothing

knotty sun
#

Stormcaller is correct.
this

if (door.destination == currentRoom)
            {
                ThirdPersonController.Instance.transform.position = door.destination.spawnPoint.position;
                break;
            }

looks like it teleports to the current room

maiden junco
#

But it doesn't happen in game

#

And if I try to freely move the position of the ThirdPersonController from the Inspector it does move

#

So it's not fixed in place

knotty sun
#

in this code
if (door.destination == currentRoom)
should currentRoom not be newRoom

maiden junco
#

But the door in question has as destination the room that I'm currently in, so its the Door of the other room, should be correct

knotty sun
#

but you are checking destination, it makes no sense for the destination to be the current room

maiden junco
#

Oh actually sorry, that foreach was for teleporting me to the position of the destination door, not the destination room

#

It could be simplified now

#

But it still should work i guess

#

Cause I have redundant references, Door A-Destination Room B and Door B-Destination Room A

knotty sun
#

still makes no sense. it's saying I'm in room A and I want a door destination == room A

maiden junco
#

Shoot, i forgot to change this:

Door[] doors = currentRoom.transform.GetComponentsInChildren<Door>();

to this:

Door[] doors = newRoom.transform.GetComponentsInChildren<Door>();

knotty sun
#

now it makes sense

maiden junco
#

Damn still it doesnt update the position

#

but at least it goes in that if statement now

rigid island
chrome trail
#

I was recently told by someone in here that continuous collision detection still works with colliders set to trigger, but this still keeps happening ("This" being that the collider keeps phasing through the wall as if it's doing discrete detection). Was I lied to or am I doing something wrong?

rigid island
#

it should work

#

how are you moving the sphere

#

just to be sure , triggers are not solid so its going to go through anything

chrome trail
rigid island
#

I asked about trigger not rigidbody 😛

#

the two are not exclusive

chrome trail
knotty sun
#

but a trigget + rigidbody will not be stopped by a collider

chrome trail
rigid island
#

well the ball is trigger so its going to go through the wall

undone crow
#

Does anyone know how to put a png on a material?

chrome trail
knotty sun
rigid island
rigid island
chrome trail
rigid island
#

correct the ball is not solid

#

it should still call a trigger enter from the ball though

chrome trail
rigid island
#

how fast are you moving it though

chrome trail
#

None of the frames have the sphere touching the wall

chrome trail
# rigid island how fast are you moving it though
    void Update()
    {
        GetComponent<Rigidbody>().velocity = Vector3.forward * 200;
    }

    void OnTriggerEnter(Collider other)
    {
        print("Trigger connected");
    }

    void OnCollisionEnter(Collision collision)
    {
        print("Collision connected");
    }```
#

I deliberately ratcheted up the velocity to something absurd specifically to test this

rigid island
#

does it work at lower speeds?

#

200* shouldnt be too bad with Continous on, but I never tried with trigger . Uusually my ball/bullet is solid

chrome trail
rigid island
#

try changing Update to FixedUpdate perhaps? might help, might not

chrome trail
rigid island
#

maybe for real fast speed you're better off using casts

chrome trail
chrome trail
spiral palm
#

if i want to save a custom type, ie. item to a binary file, how would i do that since binary can only store floats, strings, bools, and ints?

#

item holds a bunch of other values

knotty sun
rigid island
spiral palm
#

idk much about binary

rigid island
knotty sun
spiral palm
chrome trail
spiral palm
#

so i never got around to learning binary

chrome trail
#

That's the thing keeping me from wanting to do that

rigid island
chrome trail
#

Unless I just made them all the same type of collider

rigid island
#

you're not casting the collider but shapes eg, a sphere or box or line

chrome trail
spiral palm
#

but ig binary can store more

knotty sun
spiral palm
knotty sun
#

yep

spiral palm
#

that makes it so much easier

knotty sun
#

it's called binary serialization and it's pretty simple, the trick is in the serialized format

spiral palm
knotty sun
#

tbh no, I wrote my own serializer many years ago and I don't do tutorials

spiral palm
#

ah T-T oh well

rigid island
#

unity no longer supports concave physics unless its kinematic afaik

chrome trail
rigid island
#

not a cube necessarily

chrome trail
rigid island
#

if you want to test colliders / rigidbody with mesh collider at all

#

Rb.SweepTest supports whatever colliders dynamic rb does

#

not performant at all but convex shapes are part of it yes

chrome trail
rigid island
#

I never seen bullets that need some type of pin point accurate shape

rigid island
#

primitive shapes generally work fine, not sure why you'd need anything else

chrome trail
#

Something about that feels really messy to me

rigid island
#

people make bullets round sphere or capusules when in reality they are more cone shapes

chrome trail
rigid island
#

like this you mean ?

chrome trail
simple egret
#

Spheres are also easier on the physics engine, to know whether a collision occurred it just asks "is this object in that radius at this position"

#

Since a sphere can be represented by only a position and a radius

rigid island
#

yeah you're gonna have to compromise some imprecision for performance

chrome trail
rigid island
#

its not like unity would support that shape as mesh collider (w rigidbody ) without it being convex

#

which will then make it a weird half sphere thingy

rigid island
twilit scaffold
#

@spare dome I do not think Codist has any AI stuff. Should be able to run entirely offline

spare dome
spare dome
twilit scaffold
#

yeah, that is a different project entirely. different dev too

spare dome
#

alrighty 😅

#

thank you

indigo tree
#

I am struggling to find ways to order my code to appear to run simultaneous even though internally, it is sequential. For example, if I have two players that I want to update each frame, I would normally write something like this:

playerOne.UpdateLogic();
playerTwo.UpdateLogic();

Now, lets say I have logic for each player to cast a hitbox that sends the other player into a hit stun state after being hit. In this scenario playerOne would first hit opponent and force playerTwo into the hit stun state. Afterwards, playerTwo’s logic would run, but since playerTwo got put in hitstun, so her hit boxes disappeared. Instead of both players exchanging hits and being put into hit stun, only playerTwo is due to playerOne preforming his logic first.

For this specific situation, you may advise me to simply update the players’ hit stun at the end of frame like so:

playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();

Which is all fine and dandy, but we have another situation that can cause problems: players can move around, possibly dodging the hit boxes. If a player moves out of the range of the hit box at the same frame that it is cast, it will produce different results from player to player. If playerOne casts the hit box, the hit box will hit, as playerTwo’s movement has not been updated yet. However, if playerTwo casts the hit box, the hit box will miss as it has not been updated yet.

We can put a bandaid on it by having another method to run in the update to check the hit boxes like so:

playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.CheckHitBoxes();
playerTwo.CheckHitBoxes();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();

This method quickly becomes cumbersome. Each time we make these methods, we have to route our player code to wait for this method, which makes it frustrating to work with and messy. Does anyone have advice on resolving this issue? Thanks!

knotty sun
#

Have you never heard of Arrays?

indigo tree
#

would you like me to iterate through action arrays?

knotty sun
#

well

Queue<Action>[]

would seem to fit the bill

#

anytime you find yourself writing something like this

playerOne.UpdateLogic();
playerTwo.UpdateLogic();
playerOne.CheckHitBoxes();
playerTwo.CheckHitBoxes();
playerOne.UpdateHitStun();
playerTwo.UpdateHitStun();

A red light should go off in your head that you are doing something wrong

indigo tree
knotty sun
indigo tree
#

Also, isn’t a queue a collection? Why would we need an array of them?

spring creek
#

Array is per player
Queue is the player internally

indigo tree
#

I see. But shouldn’t I make players hold their action Queue in their own class so that the player’s UpdateLogic can determine what is in the Queue?

#

Well, I’m try it. Thanks guys!

maiden junco
# rigid island so whats happening now instead?

Oh I thought I answered this, anyways, I fixed it by storing the player transform, disabling the whole ThirdPersonController script, editing the position, enable the thirdpersoncontroller script

hot torrent
#

If i copy an array, like a vector3 array, then it places a super long string into my clipboard, like this one:

#

is it possible to generate that paste-able string during runtime so i can copy vector3 arrays from during runtime and directly paste them into vector3 arrays inside the editor?

hot torrent
indigo tree
#

In the inspector?

hot torrent
indigo tree
#

Copying data in the inspector uses it’s own data serialization.

#

I would suggest using json serialization instead for something in runtime, but I’ll try to find the method to get the inspector string

rigid island
#

you mean like make a Vector3 array as Json ?

hot torrent
rigid island
#

Oh just generate a string from json serialization no?

indigo tree
hot torrent
#

Yes.

rigid island
#

ohh ok

hot torrent
#

Optimally i would want it to just be a right-click > paste into the editor.

#

But if it uses a special Serialisation, that's fine, i could think of other methods.

indigo tree
#

I am pretty sure it holds more data then just converting the property to a json is the problem.

#

Otherwise you could just use a json serializer.

rigid island
#

they only mentioned v3 so I was confused

hot torrent
#

Could i write a script that generates a json object of the vector3 array, copy that json during runtime, then in the editor paste the json into a string, then when i run the script once, it turns the json object of the vector3s into a serialized array that i can then paste into the originally intended array slot?

#

would be tideous, but it would work, right?

rigid island
#

its going into another array of v3s?

indigo tree
hot torrent
#

Can't i turn a string into a json object?

rigid island
#

well yea

hot torrent
#

Hm. Then let my try that tideous method!

rigid island
#

why is the json needed at all, can you just write script that targets that specific component ?

indigo tree
rigid island
#

iirc unity has a script example on the Cinemachine component that uses a method of saving runtime values to a component in playmode

indigo tree
hot torrent
rigid island
#

if its part of the scene ofc

hot torrent
#

That's not the issue tho...!
I want to grab the v3 array i generate during runtime, and then place it into a v3 array in the editor.

rigid island
#

yeah I get that, but v3 array is on a component yes?

indigo tree
rigid island
#

i'm guessing to save the runtime values to have the object start with those values on next run?

rigid island
#

right. So just feels like serializing to json then deserialize is an extra step if you just target the specific component you want to apply the changes to

#

here is how unity does it for the Cinemachine component I mentioend

#

so like any changes made on that component persists when game is stopped

#

its a bit advanced to study though, so maybe json might be easier.

hot torrent
#

Hm. I'm gonna try something here! I'll let ya know if it worked! Thank's alot for the help :D

rigid island
#

sure thing . goodluck!

hot torrent
#

ty!

knotty sun
#

save all that pointless messing around with json

rigid island
knotty sun
rigid island
#

oh does stopping game trigger a domain reload?

knotty sun
#

the editor is a different domain than play mode, yes

rigid island
#

from my understanding they have
ScriptA => Runtime Generates say Array "a","b", "c"
stop the game
ScriptB Array=> ValuesFromScriptARuntime "a" "b" "c"

knotty sun
#

there are lots of options, saving to json is probably about the worst you could chose

rigid island
#

hah yeah this stuff is def beyond my paygrade. I'm sure you can offer a better suggestion here lol the Cinemachine one is more convoluted cause of that reflection looking stuff

knotty sun
#

you could use named or anonymous pipes to effect the same thing

rigid island
#

hope OP is keeping an eye out lol

knotty sun
#

seriously complex stuff, probably way too complex for him

rigid island
#

haha yeah also for such a simple usecase it might be over-engineered tbh

knotty sun
rigid island
knotty sun
rigid island
#

plan on having the user able to easy make levels / pathways for game mode by using editor tooling UnityChanPanicWork

unreal sage
#

Yo , i have a problem with a game

rigid island
#

it is not, this is a discord for Unity Developers, not games made with Unity Support

rigid island
#

cant send invites here or it auto mutes me 🙂

modern creek
#

How do I play an animation clip in reverse in timeline..? In the AC I could set the speed to -1 but I can't seem to to that in the timeline clip inspector

#

Oh.. you can't. 😐

rigid island
#

I just flip the keyframes 😦

#

create another clip for revers :\

modern creek
#

yeah unfortunately this animation clip (on a 3d model) was.. created by an external shop and has a keyframe every frame

rigid island
#

i hate -1 speed cause it messes with my transitions

modern creek
#

I was just gonna try that.. copied and pasted the .anim and was gonna .. just move everything around, but it seems like a huge pain

#

same

modern creek
#

😐

rigid island
#

then use the blue Handle to flip them

modern creek
#

hm.. i'll try.. i'm thinking I'm gonna F this up somehow

rigid island
#

make a clone ofc

modern creek
#

ya

lean sail
#

😉 spend 30 minutes creating a script to do this for you instead

spare dome
#

version control

#

cant say this enough

modern creek
#

obviously i have version control lol

#

just saying, this looks to be like one of those super fiddly type things where you ... mess up one keyframe and then you gotta roll back 5-10 minutes of painful clicking and moving these things around

#

this model has a looooot of animated vertices

spare dome
#

save and commit before you do this

lean sail
#

if its something you need to do often, creating an editor script for this actually might be better

modern creek
#

ok that was actually not painful at all and worked great

#

select all the nodes and there's a node at the top of the keyframe editor that just magically selects all of them

#

so I moved each node to the right (from the back, reversing them), then moved all back to 0:00

#

MoveOut is the new one I just made

rigid island
#

ahh timeline, i should probably start using that

modern creek
#

Yeah I'm ... debating whether I want to.. the way I understand it is that it's not compatible with animator controllers, which was how I was gonna manage my FSM for these guys

#

but timeline will let me do things like compose "a move" (ie, idle -> movein -> move x3 -> attack x2 -> idle) and coordinate it all with cinemachine vcam cuts, particle effects, sounds, and so on... doing it in code via dotween sequences has been tedious in the past for me

#

ie, 500 lines of code to do like.. a reward box opening

jagged plume
#

Is it an underweight chinchilla or something?

modern creek
#

ha

#

it's a mouse. 🙂

craggy oyster
#

Hey im curious on how i would handle possible tens of thousands of zombies in a 2d open world game

modern creek
#

for (int i = 0; i < 10000; i ++) Instantiate(zombiePrefab);

craggy oyster
#

Idk if dots is what i need since i dont need many zombies on screen

modern creek
#

And if that's slow.. google up object pooling

#

You probably don't need dots, but you probably will need/want object pooling

craggy oyster
#

Im not a beginner i understand how to spawn them and object pool

#

Im asking if its going to be sufficient

#

Like should i make a system where instead of having thousands of game objects

#

Just keep a track on where they are and despawn them when out of range?

modern creek
#

If you're not a beginner.. you should understand why that question is kind of impossible to answer.

It depends on the game objects and how much of the CPU and GPU they're gonna need on each tick. Physics? Colliders? AI? Textures? Lighting? 2d? 3d? There's just too many things that go into an answer like that..

rigid island
craggy oyster
#

Yea my bad ill explain

rigid island
#

many things affect performance including code

craggy oyster
#

They are just 2d sprites with animations and they will have ai functionality to follow and attack the player using pathfinding

modern creek
#

So.. I mean, I get sorta what you're asking, but your question is too broad. If you have 20k zombies in your open world game and you're concerned about rendering them, then you'll want aggressive occlusion culling, clipping planes, and level design so you can't see that many at once.

If you're concerned about pathing and CPU and AI, then you should probably only be doing AI updates when a player is within range.

rigid island
#

you can also do the pathing calculation in seperate thread if you're not using specific unity apis

modern creek
#

If they're ALL sorta moving toward the player then you'll probably wanna chunk them up and give the same pathfinding to chunks of them - ostensibly zombies that are far away are all moving in roughly the same direction, so calculate that direction once and then apply that logic to each of those 500 zombies (or whatever) in that far away "chunk"

craggy oyster
#

Im basically not sure myself on what would be the biggest cost on performance

modern creek
#

Well we aren't either, and you won't know until you build it and profile it 😛

rigid island
#

thats why we just make it, and profile. optimize as needed

modern creek
#

Might be GPU.. might be CPU, might be boneheaded pathfinding applied to 20k units.. etc 😛

#

nava timeline is awesome btw

#

check out how easy this is to string together animations

rigid island
#

I used to have a script on each of my coins rotating itself, turns out it was better to only have 1 script controlling all coins rotating

modern creek
#

if I did that in tweens.. god that'd take forever

modern creek
#

and the animations have the blending support animationcontrollers have

#

way better than trying to do that in code and work out all the timings

rigid island
# modern creek

but isnt this better for like cutscenes not soo much going into specific states like animator or am i misunderstanding ?

modern creek
#

yeah but .. I'm thinking the way I'm gonna do it is have mini "cutscenes" for something like a "move and attack" turn

rigid island
jagged plume
modern creek
#

the only real animation controller I think I'll be needing is just to set characters to idle

#

or maybe I'll use the signal emitters in timeline.. i dunno yet

#

Trying to figure out a way to make a timeline that's usable for multiple characters + .anim clips for each

#

dunno if I can do that since each animation clip refers to the meshes verticies by name, and they're not the same obv.. like if I drag one "move" clip from one character onto another animator in timeline, it doesn't do anything (obviously)

#

I think maybe the way I'll do it is.. make a timeline for the attacking character that has a signal track (which emits a signal when it does damage?) and then the uh.. playable director? fills in the details at runtime

swift falcon
craggy oyster
#

Wait does dots work with any networking solution?

broken light
#

is it possible to intercept the delete event from editor so i cannot delete a gameobject in the scene? i specifically want to prevent deletion of child objects of the parent, because if i do that by mistake it breaks stuff

#

that way they only delete if i delete the parent

modern creek
#

I override it

#
    public class BetterMonoBehaviour : MonoBehaviour
    {
        protected new void Destroy(UnityEngine.Object @object)
        {
            if (@object == null) return;
            if (@object is not GameObject)
            {
                Assert.IsTrue(false, "Inadvertently using Destroy() on a component instead of a GameObject.");
            }
            else
            {
                try { UnityEngine.Object.Destroy(@object); }
                catch
                {
                    // unlimited power
                }
            }
        }
    }
#

I inherit from my "better" monobehaviour class everywhere so I don't accidentally do something simliar - accidentally delete a component from a gameobject (which I basically never do) so I don't do it by accident

#

you could just basically do the same - new your Destroy method and just have it do nothing or whatever

rigid island
broken light
craggy oyster
rigid island
#

kinda jumping the gun if you havent profiled anything yet and just going on assumption

void basalt
#

just different flavors

void basalt
mellow barn
#

Hey y'all, I've got a video for this one... essentially, the music works the first time you run it +until you pause, after pause, the music just... doesn't play. The home button runs this code and this code:

    public void resetter(){
        settingsIsActive = false;
    }
    public static void ReturnHome()
    {
        SceneManager.LoadScene(sceneMap["Home"]);
        Time.timeScale = 1;
    }

and my pause works like this:

void Update()
    {
        
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            settingsIsActive = !settingsIsActive;

            AudioListener.pause = settingsIsActive;
            settingsUI.SetActive(settingsIsActive);

            if(settingsIsActive)
            {
                Time.timeScale = 0;
            }
            else
            {
                Time.timeScale = 1;
            }
        }
        Debug.Log(Time.timeScale);
    }

So it shouldn't be a timescale thing, should it? It also claims the music is playing for one frame on every refresh, as every time I run it the "music playing?" log goes up by 1, but it cuts out immediately afterward. NOWHERE ELSE IN MY CODE are stop or start mentioned for audio. What is going on???

relevant code to "music playing":

public void TerminalButtonPress(){
        if(phase == Phase.OPEN){
            theMusic.Stop(); //this didnt matter before, but it totally does during resets w pause button
            theMusic.time = 0;
            theMusic.Play();
            playing = true;
            noteScroller.started = true;
            Debug.Log("music started HERE");
        }
        else if(phase == Phase.CLOSE){
            levelSummary.SetActive(true);
        }
    }
``` (runs when you click that button)

..also the homescreen doesnt even HAVE an active settings manager (pause menu), so it again, really shouldn't be doing this.
#
 private void CheckGameOver()
    {
        Debug.Log("health " + healthBar.value);
        Debug.Log("settingssss?" + SettingsManager.instance.settingsIsActive);
        if ((healthBar.value == 0 || (!theMusic.isPlaying && playing)) && !SettingsManager.instance.settingsIsActive)
        {
            gameEnded = true;
            EndGame();
        }
    }

code to check if game is over, it always returns true here because !themusic.isplaying

#

But i don't know what's stopping it... I've been stuck on this for a week, any help would be extremely welcomed

spring creek
mellow barn
little meadow
mellow barn
#

So should I set it to false in my reset function?

nimble cairn
#

https://paste.ofcode.org/8biXBq89vaKcHZRVJ38Wqe

externalVelocity: the velocity/float/bob of a moving platform. I apply this to the player's velocity so they move around with the platform.
I know input/movement framerate independent; Have I multiplied TIme.deltaTime correctly? Do multiply by this many times?

Do I apply velocity.y += gravity * Time.deltaTime; every frame or just when the player is not grounded?

Do I call a second Move() to apply apply gravity/external velocity after my initial Move() call?
The player applies downwards force when landing on platforms. Do I even need to smoothing externalVelocity? I want to avoid jitter.

little meadow
mellow barn
mellow barn
nimble cairn
#

@lean sail Sometimes, I dream about cheese

lean sail
nimble cairn
#

@lean sail okay

modern creek
#

I'm just brainfarting this afternoon.

How can I create a Vector2 tween for position from X to Y with a starting velocity? essentially a tween with an ease like InExpo but with a starting velocity that isn't 0.

The use case is missiles animating out of a gun. Bonus if the missiles track the target in case it's moving.

I'm assuming I might have to bust out ye' old lerp and do something from T = -1 to 1, but play it from 0 to 1 (with DOVirtual.Float)

nimble cairn
modern creek
#

Yeah was just hoping to use DOTween's API but.. I can't find an easy way to tween from 0-1 but start at 0.5

#

I'm currently doing 0-1, dividing by 2 and adding 0.5, and starting from the inverse vector of the target, but ... the effect isn't the same

nimble cairn
#
void Update() {
        //reset when we press spacebar
        if (Input.GetKeyDown(KeyCode.Space)) {
            currentLerpTime = 0f;
        }
 
        //increment timer once per frame
        currentLerpTime += Time.deltaTime;
        if (currentLerpTime > lerpTime) {
            currentLerpTime = lerpTime;
        }
 
        //lerp!
        float perc = currentLerpTime / lerpTime;
        transform.position = Vector3.Lerp(startPos, endPos, perc);
    }
}
#

1 second let me check

modern creek
#

i'll paste my code in a sec

#

still tinkering

nimble cairn
#

I've never used DOTween before tbh. I perfer this native solution./

modern creek
#

yeah.. I know but I like DOTween because I can chain together sequences and so on easily.. I might just have to manually lerp it and do the other stuff in parallel

#

i also was hoping to not get into the business of mathing up all the easings I want - lerp is actually almost never the right one for animation

#
        public void OnFireMissileStart()
        {
            Sequence seq = DOTween.Sequence();
            Missile.transform.localPosition = _missileStartLocalPosition;
            Vector3 missileStartPosition = new Vector3(
                (2 * Missile.transform.position.x) - MissileTarget.position.x,
                1f,
                (2 * Missile.transform.position.z) - MissileTarget.position.z
                );
            seq.Append(DOVirtual.Float(0, 1, MissileFlightDuration, x => SetMissilePositionInstant((x/2) + 0.5f, missileStartPosition)).SetEase(Ease.InExpo));
            seq.Play();
        }
        private void SetMissilePositionInstant(float progress, Vector3 missileStartPosition)
        {
            Vector3 position = missileStartPosition + ((MissileTarget.position - missileStartPosition) * progress);
            Missile.transform.position = position;
        }
nimble cairn
#

@modern creek
static DOTween.To(getter, setter, to, float duration)

Have you attempted just Lerping the duration? (In which case u might as well Lerp the whole thing)

modern creek
#

that's basically what I'm doing with DOVirtual.Float

#

but.. I think I'm just having some dumb re: the starting position and so on

nimble cairn
#

I've never used this Library b4 sorry I'm not of much help

modern creek
#

I was thinking the missile start position would be the the target "in the opposite direction" and i'd lerp it from 0.5 to 1 but... I think I'm just overcomplicating this and there's an easy solution I'm not seeing atm

#

no worries - it's just the same as what you proposed, just imagine DOVirtual.Float is the same as Lerp

#

already I see one problem that I'm calculating the lerp position based on the target position - which can change over the lerp.. so if the unit is rotating while firing missles (ie - the target is moving), then the missiles in-flight are gonna go flying all over the place

#

anyway, will fix tomorrow, thanks for your eyeballs 👀

nimble cairn
#

👍

maiden stone
#

Im currently moving a gameObject to a specific distance away from the direction that the player is moving. Does anyone have any ideas on how I can make the selected part collide any object it hits, not allowing it to move through them?
This is the code that I am using to move the gameObject
selectedObject.transform.position = Vector3.Lerp(selectedObject.transform.position, player.cam.transform.position + player.cam.transform.forward * partDistance, Time.deltaTime / 0.075f);

rigid island
maiden stone
#

Is there any way to move the part without transform allowing it to collide?

rigid island
maiden stone
#

I move it using the transform to the direction the player is facing. I can send a longer code block of my entire function if required?

leaden ice
maiden stone
#

Okay thanks

maiden stone
#

Sorry for the late response, I got preoccupied with other matters

leaden ice
#

No your previous method of moving via the Transform will not work

#

To get proper collisions you need a non-kinematic Rigidbody and to move it via setting velocity or applying forces

maiden stone
leaden ice
#

Gravity is a separate topic and not really related to the current discussion

#

there's a separate checkbox for gravity

maiden stone
#

Yeah I got that now 😆

#

Anyways, I'm trying to move it to the specified location whilst colliding with any other object. This means that it would not move to that location. I attempted something like this with the RigidBody.movePosition method, and the physics do collide however the part is still able to clip through other parts. (My intentions are to remove this clipping)

leaden ice
#

Everything else will not respect collisions properly

maiden stone
#

ahh- I'm pretty new to everything, I apologize. Thanks for the assistance.

novel bough
#

I'm trying to get the country in the script using this line of code System.Globalization.RegionInfo.CurrentRegion but it give me the wrong country name on browser

spare island
#
    public void RotateSword(Vector2 _mousePosition) 
    {
        mousePos = playerCamera.ScreenToWorldPoint(_mousePosition);
        playerToMouseDir = ((Vector3)mousePos - transform.position).normalized;
        
        if (swordRb.rotation > 180) swordRb.rotation = -180;
        if (swordRb.rotation < -180) swordRb.rotation = 180;

        neededRotation = Quaternion.FromToRotation(playerToMouseDir, swordRb.transform.up).eulerAngles.z;

        if (neededRotation > 180) neededRotation = -(360 - neededRotation);

        swordRb.AddTorque((-neededRotation) * Mathf.Deg2Rad * torque);
    }
spare island
#

if i could get it to stay rotating in the same direction instead of slowing down and changing direction that'd be epic

lean sail
# spare island ```cs public void RotateSword(Vector2 _mousePosition) { mousePo...

this code looks kinda unnecessary, couldnt you just this to get the angle? https://docs.unity3d.com/ScriptReference/Mathf.LerpAngle.html
Also not really sure what you want, it doesnt actually look like its taking the longer way to me. This code doesnt care for the current torque but you'd need to factor that in if you actually wanted it to choose which direction to go based on what would be faster. Do you actually need it to rotate with torque here, where it ramps up in speed? If you could just rotate it directly, that'd really simplify things here

spare island
#

I'm not the one who who's writing the code for it so I don't know the exact reason

#

I think rotating directly would cause issues with a rigid body no?

#

we also need the sword to have a weight and momentum

#

the goal is to have a physics based sword that orbits the player and the mouse influences where it is

the sword needs to have weight and momentum and needs to keep the current behavior where the momentum of the sword actually causes the player themselves to move

#

like how in getting over it you control the hammer

#

we want it to work pretty much like that but top down

lean sail
thorn pumice
#

hey there peeps! How would you approach this? I guess some shader black magic would be the best option but i want to get your opinions:
I have a plane gameobject A with a color, lets say yellow. And I have another one B with another color, lets say blue.
So I want that when they both overlap, the overlapping section changes to green, and I can even add text on it.

What would you suggest there?

hallow scarab
knotty sun
knotty sun
distant stone
#

Hello. Can this code be used as a benchmark for comparing the execution speed of two pieces of code that do the same thing in order to find the faster (better) one ?
void Start () { Stopwatch timer = new Stopwatch(); timer.Start(); for (int z = 0; z < 10000000; z++) { //Some code here } timer.Stop(); UnityEngine.Debug.Log(timer.Elapsed); }

wide dock
#

There are some posts online about C# benchmarking which describe the process in detail

patent wadi
#

Hey so im following this tutorial ( https://youtu.be/9fa4uFm1eCE ) but when i enable my renderer feature only the ui is being rendered and i get a black screen

Inspired by the release of Hi-Fi Rush by Bethesda, I wanted to see if I could get a similar vibrant and stylized aesthetic in Unity. Little did I know, it would swiftly lead me down a rabbit hole of custom rendering in Unity and, in turn, completely overhaul my entire perception of Unity's Scriptable Render Pipelines. This video is a showcase of...

▶ Play video
deft dagger
#

hey guys, i have a code for loading a scene from addressables and for unloading it, the loading part works just fine but when i try to unload it doesnt work, i think the code is not successfully saving the scene in a scene instance for some reason

void ExamSceneOnAddressableInstantiated(AsyncOperationHandle<SceneInstance> handle)
{
    if (handle.Status == AsyncOperationStatus.Succeeded)
        _examSceneInstance = handle.Result;
}
public async void OpenExamPanel()
{
    examSit = true;
    //Screen.orientation = ScreenOrientation.Portrait;
    //MasjedScreenPanel.SetActive(false);
    //JoisticPanel.SetActive(false);
    //ShowRRoomPanel = false;
    //SceneManager.LoadScene("Rashidi");
    await Task.Delay(2000);
    OpenCursor();
    this.GetComponent<AudioSource>().Stop();
    Addressables.LoadSceneAsync("Exam", LoadSceneMode.Additive, true).Completed += ExamSceneOnAddressableInstantiated;
    //SceneManager.LoadScene("Exam", LoadSceneMode.Additive);
}
public void GotoMasjed()
{
    //Screen.orientation = ScreenOrientation.LandscapeLeft;
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;

    //gameManager = GameObject.FindGameObjectWithTag("GMScript").GetComponent<GameManager>();
    ///gameManager.MasjedScreenPanel.SetActive(true);
    ///gameManager.JoisticPanel.SetActive(true);
    //thirdPersonActivate = true;
    ThirdPersonController.thirdPersonActivate = true;
    SingleThirdPersonController.thirdPersonActivate = true;
    //SceneManager.UnloadSceneAsync(3);
    Addressables.UnloadSceneAsync(gameManager._examSceneInstance, UnityEngine.SceneManagement.UnloadSceneOptions.None, true);
    
    //TestRelay.StartGame = false;

    //GameManager.ReturnFromAmma = true;
    //InAmma = false;
    //FromAmma = true;
}```
#

this code is in 2 files

#

the firsrst which has the first 2 functions which is called gameManager

#

thats why in the GotoMasjed function it calls the instance from gameManager

swift falcon
#

I am trying to create an Orbit Origin Based movement rotation. I want to keep the old X and Z rotation in the **local axis **of a GameObject but change the Y in the local axis dynamically. The Orbit Origin currently changes the X and Y properly but i don't know how could i achieve the Y axis rotation without having problems with gimbal lock.
The locking should work with one axis too. Likely, by locking only local X, i should be able to change Y and Z.

onyx cypress
mellow sigil
#

You have the script on two objects or twice on one

onyx cypress
#

i checked

mellow sigil
#

Debug.Log("I am on " + name); <-- put this in Start

versed portal
#

Hello. I have started Coding the Meta-Part of a Mobile F2P Game. I am implementing this for the first time so just wanted to ask which pitfalls or mistakes to avoid and if there is a Good tutorial for it.

marsh mesa
#

Hello, i need a little help with something!
Im working on UI for my game, and it requires me to instantiate new buttons sometimes. These buttons should call a function with an int parameter based on which button is pressed, i want to assign a function + a parameter to a button when it's created. My question is: how do i hook up a function with a parameter to a button via a script?

#

Im basically asking how to configure this part of a button from a script

sleek bough
marsh mesa
#

That worked, thanks a ton

marsh mesa
#

acutally, there's a problem. All the buttons call the function with the same parameter, but i need them to be different for each button

#

i have six buttons, and no matter which i press, it calls a function with a 6

#

Even tho im adding buttons in the for loop

lofty summit
#

I am using the Localize String Event component to set up my localized TextMeshPro, but in editor I still have to give it some text that will later be replaced.
Is there a better way? Am I misusing the component? What do you write in the text of the TMP?

marsh mesa
grim laurel
floral needle
#

So... I need some help...
How is "this = bull ref" a thing? The object is in the hierarchy so nothing is really destoying it. I am very confused

#

and it's not another script trying to call a method without having a ref to the method's owner, it's a response to an event so if the method is getting called it means that the owner listened to the event (which means it exists to listen no?)

knotty sun
#

sounds like you are subscribing to events but not unsubscribing

floral needle
simple saffron
#

hi all, im trying to place an object on a surface and have the up direction be the normal of the raycast to find the placement position, and set the forward direction based on the direction the player is facing in
https://youtu.be/N3nzshkuLH4?si=wscRHu-ffAqNZXwu&t=165
I'm looking for behaviour that is akin to this

A detailed guide to the Medium Build's Guardian Turret Specialization and the Heavy Build's Dome Shield in THE FINALS. I look at using them individually and combined.

00:00 Intro
1:08 The Guardian Turret
11:55 The Dome Shield
15:36 Using The Guardian Turret And Dome Shield Together
17:09 Outro

Download and Play THE FINALS here: https://store.s...

▶ Play video
#

i've timestamped the link

rigid island
simple saffron
#

ah rip
(hit enter too early, one moment)
It orients fine on floors and ceilings, but on walls, it sort of sits upright, half in the wall

rigid island
#

you'd have to show what you got so far n code

simple saffron
#
                    obstructed = Physics.CheckBox(hit.point + placementObstructionBoxOffset, placementObstructionBoxBounds / 2, Quaternion.LookRotation(wm.pc.clientRotationRoot.forward, hit.normal), obstructionLayermask);
                    hologramInstance.transform.SetPositionAndRotation(hit.point, Quaternion.LookRotation(wm.pc.clientRotationRoot.forward, hit.normal));
#

ill grab a screenshot of what it looks like in the game

#

on the floor, its valid and can be placed, facing the correct direction
On the wall, it does this

#

the biggest bit Im having trouble with is the obstruction box rotation

little meadow
#

no idea what wm.pc.clientRotationRoot.forward is

#

also what's the value of placementObstructionBoxOffset?

#

you're offsetting in world space, but that value sounds like it should be local space or it wouldn't make sense 🤔

simple saffron
#

that's a valid point, thanks

#

I've gotten the direction stuff I wanted, i'm projecting the player's view direction against the plane im placing the turret on and using that in LookRotation

#

just need to orient the placed turret to match now :p

rigid island
simple saffron
#

I did, yeah :D
I'll share the code in a sec

rigid island
#

I was making a project with lasors + mirrors, I use right click to rotate but using the players view might be a better fit :p

simple saffron
#
Quaternion rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(wm.fireDirectionReference.forward, hit.normal).normalized, hit.normal);

where wm.fireDirectionReference is a reference to the camera's parent

#

so you could probably just substitute that out for the camera's forward if it works for you

rigid island
#

oh weird I had something similar but it looked strange for some reason

var itemForward = Vector3.ProjectOnPlane(cam.forward, hit.normal);
something.SetPositionAndRotation(hit.point, Quaternion.LookRotation(itemForward, hit.normal));```
simple saffron
#

im normalising mine, could that be it?

rigid island
#

ahh i see let me try that

rigid island
simple saffron
#

glad i could help :D

primal wind
#

Thought that "hey, wouldn't it be nice if people could use Typescript to do stuff in my level editor?"

#

But jint is JS only and i didn't want people to have to run TSC

#

So i wrapped it with Jint

#

and it somehow works

#

Now i'm wondering if there is some way to automatically generate type definitions from C# types

#

Considering the exposed stuff will be wrappers

#

(cause i don't wanna use AllowCLR, cause they could mess up anything)

static matrix
#

what should I do if I'd like to use FindObjectsOfType but i'd like to find all objects that instantiate a certain interface?

rigid island
#

are they different scripts ?

#

maybe change the spawn method and use an interface

static matrix
visual flare
somber nacelle
static matrix
#

i'd like to have an interface I can use to make it such that things can be altered on flash, and when I call "flash" i'd like it to iterate through all objects that have a script that uses that interface, and call OnFlash()

rigid island
somber nacelle
static matrix
#

ok
time to learn events then ig

somber nacelle
#

just have them subscribe to the event when they are instantiated

rigid island
#

events are dopee

static matrix
#

is that a c# thing or a unity thing?

rigid island
#

c#

static matrix
#

just so I know what docs to look at

somber nacelle
#

both

static matrix
#

cool

#

unfortunately for me, the c# docs for events are not great

#

(in my opinion)

static matrix
#

well, its split into a bunch of different files

#

ill figure it out, thanks for the help

swift falcon
#

I am trying to achieve a rotation that is driven by the another rotation but stuck at allowing rotation in specific axises like hours. Quaternions are such a hard thing to understand. Could you help me how can i achieve this without using Euler(gimbal lock)?
In the image, the accepted rotation is Y

Hm i believe my mistake was using literal directions. I should use Quaternion.AngleAxis() to rotate around Roll, Pitch and Yaw.

compact perch
#

hey, im fairly fresh in ECS and apparently doing something wrong or missing something obvious but after whole day trying to figure it out i finally tried just copypasting tutorial code from
https://learn.unity.com/tutorial/65b3e48fedbc2a611fc291a7?uv=2022.3&projectId=65b3d3cfedbc2a5399ce3740#65b3e534edbc2a598e6ade03
and it works, but only when subscene is loaded into liveEdit. when i untick scene (which if i understand correctly is state of actual build) i get exception:

ArgumentException: We are reading a UnityEngine.Object but the deserialized index is out of range for the given object table.

and warning:

Error when processing 'AsyncLoadSceneJob(VirtualArtifacts/Extra/a0/a0a6776b66c09598ec3fce9838e3620b.0.entities)': We are reading a UnityEngine.Object but the deserialized index is out of range for the given object table.

ig is common issue when dealing with hybrid approach and authoring monobehaviors, but im totally lost on how to register EntityPrefabs outside live edit. Any point to right tut or advice appreciated.

#

also tried using EntityPrefabReference from docs, similar results with error that AddComponent was used on Entity.Null

compact perch
#

Got it, sorry

spring creek
#

No worries, they will just likely have the best advice

cunning burrow
#

is Time.time UTC?

#

or is it timezoned?

rigid island
#

its just a float

rigid island
cunning burrow
#

my server is passing the time in this stupid string format, I parse to DateTime and then I can get the float from that, I am wondering if I can then subtract Time.time from it and get a delta between the two times

#

wait Time.time is runtime seconds

rigid island
cunning burrow
turbid willow
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

rigid island
turbid willow
#

where do i ask for help regarding issues i have with my vs and unity?

cunning burrow
rigid island
#

what do you need to do exactly

cunning burrow
#

emm, no

#

if it were working like this I would have done it so :3

spring creek
#

Well show how you parsed it?

rigid island
#

if you explained the usecase we can probably provide better fix

cunning burrow
#

and datetime is not serializable as you can see

#

while my class is serializable, and parses it to a DateTime

weak perch
#

How do you serialize a sprite?

#

I need to be able to use it in a network variable but it won't run through serializer

leaden ice
weak perch
#

Hmm, I might have to rethink the way i'm doing it then

leaden ice
#

What are you trying to do

cold parrot
#

The other side should know statically what sprite to use depending on the command/choice you send.

weak perch
#

And it's a scriptableobject so i can create many

#

So i'd need to serialize all data in it

#

The only thing i can't do is the sprite

leaden ice
#

An item id or the item name

#

That's it

#

Both sides already have the ScriptableObject assets

#

There's no need to serialize the whole thing

weak perch
#

I see what you mean yeah

#

How would you do that? Would i have to create a list of all scriptableobjects and load it from there?

weak perch
#

I already have a global items table and each item has a unique name, so its probably the easiest way

#

Thank you

leaden ice
broken light
#

am i being dumb, i have [SerializedField] on a class that is just a regular plain C# class but the inspector is showing me an inspector element like when its expecting a scriptable object

#

oh i was being dumb

#

nevermind

foggy pasture
#

heya, sorry for the package specific question but this one is fairly popular and doesn't seem to have a discord- is anyone familiar with magica cloth 2? I can place my model in their demo scene and it'll work with meshcloth, but the instant I put it in my own scene instead it doesn't work, even though the gameobject with the mesh is 1:1 in both scenes

crude mortar
# cunning burrow my server is passing the time in this stupid string format, I parse to DateTime ...

honestly depends on what you are trying to do with the time. A time "delta" only makes any sense of the two times are related in some way. This datetime could be anything (could be the real life time it was sent, or it could be the time since the server started, etc). Time.time is the time since the Unity application has started, so if it makes sense to make a delta from that, then yes nothing is stopping you from subtracting a float from a float

foggy pasture
swift falcon
clear mist
#

I'm trying to make the camera keep both players on screen at all times, zooming in more when they're closer and zooming out with distance, but the stuff I'm finding online is outdated and doesn't work, so I'm having difficultly trying to figure out how to do this.
The effect I'm going for would be like in fighters like SF or DBFZ.

clear mist
#

I see, I'll play around with this, thanks!

clear mist
#

I messed around with it but this seems to place the camera directly inbetween P1 and P2, i tried adding a third object to pull it back which works but then it's not centered between them

rigid island
weak venture
#

hey im looking at adding some automated testing to my game. Do people have good experiences with the unity test framework or are there 3rd party frameworks youd reccomedn instead?

fathom cloud
#

How do i make it so that it only destroys game objects with a certain tag

spring creek
fathom cloud
#

i know

spring creek
#

Then what question do you have?

fathom cloud
#

im just kinda new to unity so idont know how to implament a compare tag

spring creek
#

It is as simple as putting it in an if statement and plug in the tag

fathom cloud
#

ok

spring creek
fathom cloud
#

thx

#

i followed it but it still isnt working, is there anything i missed or still need to add?

#

nvm, fixed it mb\

spring creek
#

Was the issue that the collider did not get changed to isTrigger?
I notice you changed to OnTriggerEnter

fathom cloud
#

ye

#

i just forgot to enable is trigger

spring creek
#

You CAN keep it in OnCollisionEnter if you wanted

#

collision.gameObject.CompareTag()

fathom cloud
#

ok

#

is there a way to delete the bullets if they get too far away?

inner charm
fathom cloud
#

ok thx

#

And i am trying to bake my mesh but i csnt click on navigation

tranquil canopy
#

I don't know if this is allowed, but I don't exactly know if it's a code question or a UI one, so then i paste it here, hopefully anyone could help me: #🧰┃ui-toolkit message

cosmic rain
knotty sun
marsh wadi
#

hey, in 22.3.40f1 we have this stackoverflow when opening a particular scene, does that sound familiar to anyone?

tribal jay
#

hey, can someone tell me whats the difference between using a singleton like this: Singleton<ClassName> and making and instance like this: public static Instance ClassName?

mellow sigil
#

Can't tell for sure without seeing the code for the Singleton class but presumably it's a generic way to make singletons without having to implement the mechanics separately every time

gray mural
lapis pebble
#

Hey everyone!
I want to create a script that shows/hides a SerializedField in the inspector when certain conditions are met.
For example:

if ("gameObject" the script is attached to has a material that uses a Normal Map)
{
Display the SerializedField variable to be modified in the inspector;
}
else
{
Hide it;
}

#

Has anyone tried to replicate this similar idea to mine - or am I asking for something impossible?
(asking for a friend)

knotty sun
crisp minnow
#

Trying to get Client.Embed code to run in order to embed a Unity Package I have. The package itself has compilation errors and publishing the updates to verdaccio is not available atm (colleague who has access to do this will be returning in a few days). I wanted to embed and update this locally but due to the compilation errors, Unity doesn't seem to want to play along and let me get the embed code to show up:

    [MenuItem("REDACTED/Advanced/Embed REDACTED Package/REDACTED.Backend/REDACTED.REDACTED")]
    static void EmbedPackageMenuItem()
    {
        const string PACKAGE_NAME = "com.REDACTED.REDACTED.backend.REDACTED.REDACTED";
        REDACTEDUnityPackageEmbedUtil.SetPackageAsEmbedded(PACKAGE_NAME);
    }

The above otherwise works fine (when Unity doesn't have compilation errors)

marsh wadi
static pollen
#

I tried scaling up the ground distance

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

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 10f;
    public float gravity = -9.81f;
    public float jumpHeight = 5f;

    public Transform groundCheck;
    public float groundDistance = 5f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        Debug.Log(isGrounded);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");

        Vector3 move = transform.forward * x * speed;

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move((velocity + move) * Time.deltaTime);
    }
}
#

here's the code

static matrix
#

is this a pointers moment
i'd like to have a function that can determine which variable to edit
if this is ludicrously hard to set up, ill just do it the messy way with an individual if check

knotty sun
static matrix
#

well does this give me the value of the given variable dependent on the conditions, or edit the given variable dependent on the factors

knotty sun
#

that code does nothing with factors

static matrix
#

im hoping to write a function that will keep me from if checking for every specific variable here
trying to condense four if checks into one
is there like a way I can combine ref and return?
like i'd love if I could return a reference to a variable

leaden solstice
#

Why not use property?

static matrix
#

figured it out
that was
quite easy actually

#

I feel silly for coming here, sorry for bothering

#

sheer dopamine rush of writing code with a new skill

#

and it works perfectly

#

thanks for helping me rubberduck this lol

bronze crystal
#

i have this game where you let enemies slide by titling the platform, any advice on how to make it more controlable when tilting in reverse

knotty sun
#

modify your physics materials, you probably want to constrain the rotations on the capsules as well

#

and please dont post videos from a phone

static matrix
#

AllAnoms.RemoveAll(item => item.IsActive);
i'm not very experienced with linq, this should remove all items that have IsActive set to true correct?

bronze crystal
knotty sun
static matrix
#

I would post the "professionals have standards" gif but dyno would eat it 😔

knotty sun
static matrix
#

well I presume its going to be at least somewhat more efficient than just doing a foreach loop

knotty sun
#

absolutely not

static matrix
#

really????
huh
well I presume this isn't going to eat 2 billion frames (especially because its only called like once a minute) but out of curiosity, how would I do this faster?