#archived-code-general

1 messages ยท Page 418 of 1

thin aurora
#

Or whatever its called

heady iris
#

in normal game development, you'd just...add the dependency

thin aurora
#

Note paths are relative to the executable so maybe you made a mistake there

#

But as per the rules we can't help you further when modding is involved

#

Even Bepinex, even if the game allows it I believe

jade belfry
#

Is there any way to make a world-space canvas only render to a certain camera without using layers?

heady iris
#

Depending on the render pipeline, how you do this will vary

#

so, you'll react to each camera being rendered by either enabling or disabling the canvas

jade belfry
heady iris
#

Unity calls OnPreRender after the Camera performs its culling operation. This means that if you make a change that affects what the Camera sees, the change will take effect from the next frame. To make a change to what the Camera sees in the current frame, use MonoBehaviour.OnPreCull.

#

(this is for OnPreRender, not for the SRP's callbacks)

jade belfry
# heady iris oh, yes, it does help to read the documentation...

oh no it don't

  1. Using URP
  2. There's no pre-culling callback for SRPs afaik. I tried using RenderPipelineManager.beginCameraRendering before something where and it doesn't work. Disabling canvas, disabling the object itself, doesn't work.
  3. I'm 90% sure the draw calls are prepared for the canvases really early on, at PostLateUpdate, unlike all other types of renderer, and any camera callback happens before rendering, too late to change what's already been prepared.
heady iris
#

I was jabbing at myself there :p

#

Does disabling other kinds of renderers work with beginCameraRendering?

#

or is it a complete bust for everything?

jade belfry
#

:<
Why are canvas such a black boxes
Disabling individual Canvas Render is a bust, will disable it for all camera.

heady iris
#

oh, I meant to turn off a mesh renderer, just as a sanity check

jade belfry
#

Oh that should work

#

I haven't checked lemme check

junior dock
#

Ok guys so il ltry to do the github tommorow. but for now ill try something different.. So the problem is taht he cant see my projects while he is on my acc. Is there a way so he can see it? do i need to send the file to him and how?

heady iris
#

this is not a code problem

junior dock
#

@thin aurora @rigid island

thin aurora
#

Yeah not really for this channel

#

I don't know either

rigid island
heady iris
#

ah, that's a static event

jade belfry
jade belfry
#

That's just an event for the canvas itself :(

heady iris
junior dock
heady iris
junior dock
#

thanks

heady iris
jade belfry
#

Aight thanks for trying :<

rigid island
#

!collab

tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข Collaboration & Jobs

ionic grove
#

Do you guys know any way to detect whether a UI element is over any other UI elements and how to tell which one it is? Example in screenshot being the reticle being over that white square. The reticle can move, so I want to tell which white square it's over.

somber nacelle
#

use the event system to raycast against the UI

pulsar plinth
#

I'm having trouble downloading the Google.Protobuf namespace for C#
how do I do that?

ionic grove
# somber nacelle use the event system to raycast against the UI

private List<RaycastResult> GetUIElementsUnderPoint(Vector2 reticlePosition)
{
    List<RaycastResult> results = new();

    PointerEventData pointerEventData = new(eventSystem)
    {
        position = reticlePosition,
    };

    print("Reticle Pos: " +  pointerEventData.position);

    raycaster.Raycast(pointerEventData, results);
    return results;
}

This is the method I'm using

pulsar plinth
ionic grove
ionic grove
somber nacelle
#

why? just use the EventSystem

ionic grove
somber nacelle
#

if you have more than one canvas in your scene then using a specific GraphicRaycaster won't be sufficient, using the EventSystem will raycast from all of them

somber nacelle
ionic grove
#

Lol well it's still returning no UI Elements

#

The reticle I have on my UI is over an element, but it's not picking anything up.

#

Here it is clearly over the element

somber nacelle
#

and what debugging have you done for this

ionic grove
plucky inlet
somber nacelle
ionic grove
plucky inlet
ionic grove
elfin tree
#

I'm making a game that has 2D characters in a 3D world. What's the best way to place sprites/images in world space knowing they will use a billboard effect?
Should I make a separate world canvas for each character?

(could not find the right channel to post this)

plucky inlet
brave furnace
#

I'm looking for some help with Zenject. Is this the right channel for it?

tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

brave furnace
#

more like, it's not a Unity specific issue, but one for a commonly used package for Unity, hence the question ๐Ÿ˜›

plucky inlet
brave furnace
#

I'm currently playing around with Zenject because I think dependency injection would solve quite a bit of my hardcoded dependencies.
I got it to work in a test project, it went fairly smoothly, but I don't understand when and how it actually does the injection. A regular program would inject everything before actually running the app, but Zenject needs to do some voodoo magic to get it to work with Unity.
The git/asset store page seem to imply that you can also inject at runtime because of it, but I am struggling to get this to work.

#

Could someone explain how I could achieve this?

wheat cargo
#

Not answering your question here, but just be aware Zenject has not been updated in quite some time, like years at this point

brave furnace
#

I know, and I'm currently using Extenject, but that was updated in 2021 or so

wheat cargo
#

I personally wouldn't use something not actively maintained that is so deeply embedded in my architecture

brave furnace
#

do you have a DI tool you'd recommend otherwise?

wheat cargo
heady iris
#

singletons ๐Ÿ˜‰

brave furnace
#

cuz like I said, I did some testing, but haven't incorporated it yet

heady iris
#

I'll eventually bump into something where I wish I had more elaborate techniques

brave furnace
#

that's a service locator, Fen ๐Ÿ˜›

#

you can go nuts on those too

wheat cargo
#

VContainer seems to be actively maintaned but I have not used it myself

plucky inlet
#

yeh, its latest update is from dec 24

brave furnace
#

honestly, VContainer might just do what I need as well.

#

gonna read up on the documentation some more

subtle tinsel
#

I was trying refactoring my game into dots for entity from regular mp and made new branch for it. I gave up after awhile and now when returning to the old branch, all my scene hierarchy objects are gone... I can only see old scripts, is there a way to fix it ?

hardy sleet
plucky inlet
subtle tinsel
#

yes both vs code and unity

plucky inlet
#

probably delete the library folder too

subtle tinsel
#

anything else ?

plucky inlet
subtle tinsel
#

its still starting

#

again, same

plucky inlet
subtle tinsel
plucky inlet
subtle tinsel
#

omg, so unity creates whole ui and all game objectes in a file called scene thats whats it for

#

I can actually create then different ones for menu adn not put everything in one scene

#

I found it ty I am so dumb

plucky inlet
tawny elkBOT
#

:teacher: Unity Learn โ†—

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

subtle tinsel
#

ty I will check out some guides, it rly feels like I am going with my head through stuff sometimes

wintry crescent
#

I have an editor tool (super huge, not made by me) that consistently crashes unity 6.
The problematic function is this (look screenshot below), although obviously it's not the full code. Specifically running the ShowAsDropDown function crashes unity. There is nothing after that line, in the tool. The class here is EditorWindow, which is opened from within a PropertyDrawer.

Anyone has any clue where to look?

Inside editor log, that's all I get regarding the crash:

Obtained 22 stack frames.
#0  0x005fb67436071c in burst_signal_handler(int, siginfo_t*, void*)
#1  0x00741d43f191d0 in (Unknown)
#2  0x00741d40e2b14d in (Unknown)
#3  0x00741d3f6b3943 in (Unknown)
#4  0x00741d40e4c15e in (Unknown)
#5  0x00741d40e1a490 in (Unknown)
#6  0x005fb6749c5fe9 in PresentContextGL(ObjectHandle<GraphicsContext_Tag, void*>)
#7  0x005fb674a03592 in WindowGLES::EndRendering(bool)
#8  0x005fb675d28edb in GUIView::OnInputEvent(InputEvent&)
#9  0x005fb675c8dc66 in GUIView::ProcessInputEvent(InputEvent&)
#10 0x005fb675d27fcd in GUIView::DoPaint()
#11 0x005fb675d2a1ee in GUIView::RepaintAll(bool)
#12 0x005fb6755f7d99 in Application::TickTimer()
#13 0x005fb675cffe9e in MainMessageIteration(void*)
#14 0x00741d446de559 in (Unknown)
#15 0x00741d44741257 in (Unknown)
#16 0x00741d446df287 in g_main_loop_run
#17 0x00741d44be4d7f in gtk_main
#18 0x005fb675cfe2dc in main
#19 0x00741d43f01e08 in (Unknown)
#20 0x00741d43f01ecc in __libc_start_main
#21 0x005fb673bb9029 in (Unknown)
Launching bug reporter
#

I'm not very experienced with editor tools, and the person who wrote this enormous 1000+ line tool is not at the company anymore, so I'd appreciate anything

wintry crescent
#

Beyond that, I know as much as you, friend

#

Ohhhh, progress! Turns out the issue is inside CreateGui actually, and it's within this rootVisualElement.experimental.animation.Start block... somewhere

#

I should mention everything worked on 2022.3, but unity 6 is clearly problematic

#

yupp, removing the line fixes the issue. Any idea why this crashes unity so insanely hard? I recognize this is an experimental package, but damn, didn't expect that

plucky inlet
wintry crescent
#

no relevant packages to update, it seems

plucky inlet
wintry crescent
plucky inlet
#

unity 6 beta and alpha I see here

#

Ah and 6, still confused by this dropdown filtering out the current selected ๐Ÿ˜„

plucky inlet
plucky inlet
#

what you just replied to ๐Ÿ˜„

wintry crescent
#

simply running the RootVisualElement.experimental.animation.Start crashes unity HARD. I'm not able to get a debug out, and I have no clue what I'd debug out anyway

#

you can see pretty much all the values in there anyway

plucky inlet
#

Just wondering about the values being used like TargetHeight

wintry crescent
wintry crescent
plucky inlet
#

And is it value valid? Also, can you try to just run any other public method of animation?

wintry crescent
wintry crescent
#

so simply creating the animation object doesn't destroy everything utterly

plucky inlet
#

for testing, can you remove the onValueChanged method and see what happens?

wintry crescent
#

ToString() worked too

#

although... maybe the NaNs have something to do with this

plucky inlet
plucky inlet
leaden solstice
wintry crescent
#

I know as much as you do mate

#

the person who made it left the company

plucky inlet
#

Well, as you are using it and its not supported anymore, its yours now ๐Ÿ˜„

heady iris
leaden solstice
wintry crescent
leaden solstice
#

the size variables looks like just local or instance variable or something

plucky inlet
#

so the onvaluechanged callback and the animation start is working

plucky inlet
#

I assume, TargetHeight * Time, which might be 0 on start could kill the rendering of the elements

heady iris
#

That does sound plausible

wintry crescent
#

first call didnt have 0

plucky inlet
#

What exactly did you log?

wintry crescent
leaden solstice
wintry crescent
#

I added that + Vector2.one*0.01f as an experiment if minsize == maxsize is the reason

leaden solstice
#

That's just defining the possible size of editor window

wintry crescent
heady iris
#

it sounds like this is making the window resize to match the size of the root element

leaden solstice
#

At least it's likely expect you to do something with element there

heady iris
plucky inlet
#

could you just hard code the min amd maxsize to 100 and see, what happens?

#

@wintry crescent

heady iris
#

that's what I'd do next

wintry crescent
#

doesn't crash unity

leaden solstice
#

Unity may just not doing anything when value doesn't change

plucky inlet
#

okay, next thing I would try. Create the vector2s outside of the animation.start function and just overwrite the x and y values and assign the vector to the min and maxSize

heady iris
#

I wonder if TargetHeight is going to some bonkers value (such as NaN) because it depends on the size of the editor window

#

there was a mystery NaN earlier

plucky inlet
wintry crescent
heady iris
#

right, but you aren't setting the min/max sizes there

#

otherwise the editor would've crashed

#

i guess there wasn't a crash there, though

wintry crescent
#

interesting thing, this does NOT crash the editor

#

but this does!

plucky inlet
#

Oh boy...

#

You are creating a min and Maxsize of the same size. Leaving 0 or NaN space left

#

just for testing, could you just add + 10 to maxSize?

heady iris
#

that doesn't make sense -- those are the size limits of the window

#

if they're the same, then the window has a fixed size

plucky inlet
#

I imagine this creating some kind of quad with minSIze being top left and max being bottom right. If you are bringing those to the same points, they are leaving no space. Is that wrong?

wintry crescent
#

this does not crash the editor

plucky inlet
#

So your sizes cant be of the same size I guess

wintry crescent
#

FRIENDS YOU WILL NOT BELIEVE THIS

#

THIS DOESN'T CRASH THE EDITOR

#

but this does

plucky inlet
#

haha, so maxsize before minsize works? That is def. a design flaw in the system ๐Ÿ˜„

wintry crescent
#

yep XD

heady iris
#

meanwhile

#

I have set my window's size to zero

#

it is GONE

plucky inlet
#

great ๐Ÿ˜„

wintry crescent
#

not sure what you expected there lmao

plucky inlet
#

I just wanted to prove me wrong ๐Ÿ˜‰

#

well, Id say, write a bug ticket for this, as this does not seem right to me.

heady iris
#

I can't cause a crash just by setting the sizes

plucky inlet
heady iris
#

yeah

#

it may depend on this being an animation

wintry crescent
heady iris
#

i'm trying various combinations of sizes

plucky inlet
wintry crescent
#

I have a backlog of like 3 unity bugs

#

that I have to make a simple project that replicates them

#

and report them to unity

#

but it's soooo muuuuch woooork

heady iris
#

i've gotten a few weird graphical problems fixed

plucky inlet
#

well, im out of this conversation

wheat cargo
wintry crescent
#

overriden getter/setter

heady iris
wheat cargo
#

Ah lol

plucky inlet
heady iris
#

I wouldn't expect Burst to be involved..

leaden solstice
#

So simply setting minSize bigger than maxSize cause crash?

#

Not related to animation I assume

wheat cargo
plucky inlet
#

I still guess, the multiplication of 0(time) on minsize crashes it

wintry crescent
#

if someone can replicate and report that bug, I'd be eternally grateful

#

but I am going to sleep

still jungle
#

looks like it require minSize to be set first and the maxSize seems to be property that use minSize value which defaults to 0 and cause problems?

wintry crescent
#

debugged it out and checked

leaden solstice
#

If you set maxSize first, maxSize remains bigger

plucky inlet
#

Good call there. That might be the issue

wintry crescent
#

no it doesn't, it's normalised time between 0 to 1 start to end of animation, as far as I can tell

#

and it just doesn't call on t=0

plucky inlet
#

cathei already might have the right answer. you set first minsize and then maxsize. And somehow, for whatever reason, it does not like minsize being bigger than maxsize probably

wintry crescent
#

I mean yea that's what my screenshots showed

#

anyone replicated the issue?

plucky inlet
#

nah, its soooo muuuch wooork ๐Ÿ˜‰

wintry crescent
#

and that's understandable!

#

;D
anyway, goodnight ^^ ping me if anyone here submits a bug report pls, so that I'll know to not do it if I somehow remember tomorrow

plucky inlet
#

good night there

wheat cargo
#

If Unity were to solve this, it seems like they need to cache the property sets and apply them in the correct order after the lambda executes

#

That sucks to implement on their part honestly

leaden solstice
#

..Or they could adjust maxSize when minSize set to bigger size

#

And vise versa

#

I doubt that animation features are intended to use with those properties anyways

wheat cargo
#

Yeah true

heady iris
#

I was unable to cause any crashes even with minSize exceeding maxSize

plucky inlet
# wintry crescent ;D anyway, goodnight ^^ ping me if anyone here submits a bug report pls, so that...

Sorry, I just could not reproduce the issue. This one does not crash at all

using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEngine.UIElements.Experimental;

public class AnimationEditorWindow : EditorWindow
{
    static AnimationEditorWindow window;

    [MenuItem("Window/Animation Editor")]
    public static void ShowWindow()
    {
        window = CreateInstance<AnimationEditorWindow>();
        window.ShowAsDropDown(new Rect(100, 100, 100, 100), new Vector2(500, 300));
    }

    private void OnEnable()
    {
        VisualElement element = new VisualElement();
        element.style.width = 100;
        element.style.height = 100;
        element.style.backgroundColor = new StyleColor(Color.cyan);

        rootVisualElement.style.backgroundColor = new StyleColor(Color.yellow);
        rootVisualElement.Add(element);

        ValueAnimation<float> animation = rootVisualElement.experimental.animation.Start(
            0.0f,
            1.0f,
            550,
            (element, time) =>
            {
                window.minSize = new Vector2(20f * time, 20 * time);
                window.maxSize = new Vector2(10f * time, 20 * time);
            }
        );

        animation.Ease(Easing.OutBounce);
    }
}
#

Guess there is something going on with the rest of this system or a personal bug ๐Ÿ˜„

wheat cargo
dense pasture
#

its very brief but the lightning arc appears out of position momentarily when activating it

hollow ridge
#

the lag spike?

dense pasture
#

weird

hollow ridge
#

check the unity profiler

#

there should be a spike and u can see what it is

#

if its consistent that is

dense pasture
#

think it was just obs lagging for a sec at just the right time

#

is it just not updating its local position in the parent while inactive or something?

quick token
#

what's the difference between this and just having the while loop on top? i've never seen this before

somber nacelle
#

do while runs the content of the loop at least one time then checks the condition and breaks the loop once the condition is false

dense pasture
#

you've never seen a do while?

quick token
#

nope. first time i've seen it

dense pasture
#

guh i am old

#

its super rare but its useful sometimes

heady iris
#

Does anything set the position of the lighting object?

quick token
dense pasture
rigid island
quick token
# dense pasture

i dont think you need SetActive at all here. if you make the prefab active than it'll be active when instantiated.

heady iris
#

Is it a particle system?

heady iris
dense pasture
#

its a free asset

heady iris
#

Ah, I think I see it.

#

I bet that script sets the line renderer's points

dense pasture
#

well, its using reference objects for the points

#

you can hard set the values

heady iris
#

Depending on execution order, this could mean that you see the wrong points for one frame

dense pasture
#

could try that

heady iris
#

especially if the line renderer is set to use world space

dense pasture
#

ah, yeah it is

#

i tried turning that off but it doesn't work at all then

heady iris
#

Can you manually cause the Lighting Bolt Script to update?

dense pasture
#

possibly!

heady iris
#

actually, I'd just have it update itself in OnEnable

dense pasture
#

it has a "manual" mode too

#

time to see if theres docs (not getting my hopes up)

#

ah yeah take off world space and use hard coded vectors it works

#

thanks all

heady iris
#

That sidesteps the issue entirely

dense pasture
#

yep!

dim umbra
#

Asking this here because I think it's more of a coding problem then a UI one:
Currently, I have a dialogue system where a letter is added to the string of a text object every frame. however, this causes an issue when you get to the end of a line while in the middle of a word. The word will start writing on the original line for a few frames, then switch to the next one once it runs out of space. I tried to fix it with manual line breaks, but they look sloppy and I can't use them with the justified style. What can I do so the letters fill in exactly how they appear in the end without changing the spacing during the animation?

#

the way I want it to look the whole time:

#

the way it looks during the middle of the animation before the spacing changes:

heady iris
#

instead of adding text, you can animate maxVisibleCharacters

dim umbra
#

ooh

#

thats exactly what i need

#

thanks

lucid brook
#

I just started getting this error transform.position assign attempt for 'Player' is not valid. Input position is { NaN, NaN, NaN } after I moved my ledge climb to a coroutine.

private IEnumerator LedgeClimb()
{
    grabbed = true;
    playerMovement.RigidBody.isKinematic = true;

    currentClimbSpeed = climbSpeed;
    currentClimbDistance = Vector3.Distance(this.transform.position, climbDestination);

    while (currentClimbDistance > minClimbDistance)
    {
        playerMovement.isGrounded = false;

        this.transform.position = Vector3.MoveTowards(this.transform.position, climbDestination, currentClimbSpeed * Time.deltaTime);

        currentClimbDistanceProcentage = 1 - currentClimbDistance / climbDistance;

        currentClimbSpeed = climbSpeed * climbSpeedCurve.Evaluate(currentClimbDistanceProcentage);

        currentClimbDistance = Vector3.Distance(this.transform.position, climbDestination);

        yield return null;
    }

    grabbed = false;
    playerMovement.RigidBody.isKinematic = false;
    playerMovement.RigidBody.linearVelocity = Vector3.zero;
}
hollow ridge
#

I solved this by adding a rich text thing that made the characters invisible until the right time

#

that would've been so much easier

heady iris
#

where does that get set?

#

or is that a constant?

lucid brook
heady iris
#

Those errors about NaNs can be really annoying

#

you don't get a stack trace; I think it catches the problem later on

lucid brook
#

yeah I don't remember ever getting one before, they are very unclear in what it wanted from me. when I double clicked on it it also send me to the line above it. The Vector3.MoveTowards one, which didn't help

lucid brook
#

I'm back, with more questions Tongue2
I'm having some issues when it comes to moving my player up and down slopes. My player hovers slightly off the ground to make moving over small bumps smoother but as soon as I walk up a slope the player gets pushed into the slope instead of neatly going up it. Even though I use Vector3.ProjectOnPlane() the DrawLine even shows the normal of the force correctly, but the player is still pushed against the slope instead of up it. https://gyazo.com/eda0309a9fd16b23422e9c8de943afd5

Relevant PlayerHover Code ```C#
onSlope = Vector3.Angle(Vector3.up, groundHit.normal) != 0;
slopeAngle = groundHit.normal;

`Relevant PlayerMovement Code` ```C#
if (playerHover.onSlope)
{
    velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
    Debug.DrawLine(this.transform.position, this.transform.position + velocityChange.normalized, Color.red, 5f);
}

ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;

rigidBody.AddForce(velocityChange, forceMode);
jolly pulsar
lucid brook
jolly pulsar
#
if (playerHover.onSlope)
{
    velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);

    // small force upwards to counteract being pushed into the slope
    velocityChange += playerHover.slopeAngle * 0.2f; 
}


ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;
rigidBody.AddForce(velocityChange, forceMode);``` idk my best gusse lol
lucid brook
#

that works kinda, though if I now stand still on the slope I slide down it. which is..... weird. Also this makes going down the slope worse.

jolly pulsar
#

cuz gravity is still acting on the player and its still not working for down?

#
{
    
    velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);

    if (rigidBody.velocity.magnitude < 0.1f) 
    {
        rigidBody.velocity = Vector3.zero; 
    }
}``` this should work
lucid brook
#

Without the velocityChange += playerHover.slopeAngle * 0.2f; the player stays on the slope just fine.

jolly pulsar
#

ahh i see

#

mb for runnin you down wrong path

lucid brook
#

no worries

jolly pulsar
#

gusse i have much much more learning to go lol

lucid brook
#

oh hard same

jolly pulsar
#

although most of c# is pretty simple jus math i cant do or vectors

vast ember
#

If I want to make a grid system on an Uneven Terrain for Tower Defence, how would I proceed?

jolly pulsar
#

or anything that deals with math vectors and moving stuff using math

lucid brook
#

wait until you get to quaternion

jolly pulsar
#

we love kek

jolly pulsar
#

yea my mind cant handel that for 2 hours id go play a game or sum shi ๐Ÿ˜ญ

woven pendant
#

i have a question, how does subnautica remove bits of water from the sea when the player makes rooms?

mellow eagle
cosmic rain
woven pendant
#

when ur in the water u can swim

cosmic rain
# woven pendant when ur in the water u can swim

So, they use triggers or colliders to define water. When you add a room, they either remove a water area trigger or add a non water area trigger. The rest is pure logic in code.
It could be a bit more complex than colliders. They might be keeping a spatial data structure that defines the type of areas in the game or something like that. The concept is the same as with triggers though.

#

That's just a guess though. There are many ways to implement the same thing. No one would be able to tell you without seeing the game source code(aside from maybe the devs).

naive swallow
#

Pretty sure it's the opposite. Everywhere is water. They define "not water" areas inside of it

#

When you're in an "air" trigger, you can walk. Otherwise, you swim

cosmic rain
#

Yeah, that's just details of implementation

dense pasture
worldly hull
#

if u instantiated a prefab under ExecuteInEditMode , but u wanna connect it back to the prefab, is it like this?

GameObject spawnedObj = Instantiate(prefabs[0], transform);
PrefabUtility.RevertPrefabInstance(spawnedObj, InteractionMode.AutomatedAction);```
somber nacelle
#

did you read what that method does? because no, that would not be it. but you're on the right track, double check the PrefabUtility class

worldly hull
#

okay

prime lintel
#

it seems i did not.... ๐Ÿคก

worldly hull
#

i found instantiateprefab

#

but it needs to be spawned inside a scene right?

#

the script im working is an automated script designed for making prefabs

somber nacelle
#

if you want to save a gameobject as a prefab asset there is the SaveAsPrefabAsset(AndConnect) method, if you want to connect a prefab instance in the scene (like one you instantiated) back to the original prefab there is ConvertToPrefabInstance

worldly hull
#

ohhhh ty๐Ÿ‘

wintry crescent
#

I have a method call like this one
EventBus.InvokeEvent<TimerEvents.TimerPauseEvent>(new(pauseTimeLeft));
what would it take to get rid of the new keyword entirely, and just have the pauseTimeLeft as a parameter?

#

oh, I should mention - the parameter of InvokeEvent is of type T, that is specified in the <> brackets

#

hence the option to have an implicit "new" there in the first place

#

and since it can be implicit, it could potentially be gone... too? maybe?

cosmic rain
#

I assume pauseTimeLeft is just a float?

wintry crescent
wintry crescent
#

I wanna have LESS typing not more ;P

cosmic rain
#

Well, you can only pass in an instance of T.

cosmic rain
wintry crescent
#

very!
also it just looks ugly

#

also also, it's an interesting problem

cosmic rain
#

You could implement implicit conversion of float to your parameter type.

#

Though it's gonna be more typing

wintry crescent
#

what if I have an event that takes in 2 parameters, though

#

in the constructor I mean

cosmic rain
cosmic rain
#

You could use args array and parse it somewhere else. But I wouldn't recommend that

wintry crescent
#

yeah, I was thinking about it, but it has literally zero type safety

#

which is definitely not what I'm going for

cosmic rain
#

If it didn't have type safety you could cast it to any type and get messed up data.

wintry crescent
#

yeah but it'll be possible to pass in an incorrect args array

cosmic rain
#

For sure.

#

This is exactly what prevents doing what you want.

wintry crescent
#

yeah but I want to remove the new keyword AND retain all its benefits ;D

#

I think it's impossible without doing some code gen or REALLY scary reflection so I think I have to abandon the idea though

#

possibly both

late lion
wintry crescent
#

that's precisely what I'm going for

#

it's just that this pesky "new" is required in the first option

#

that makes things a bit uglier than I'd like them to be

cold parrot
#

Being clever like that gets you murdered by colleagues in your sleep.

wintry crescent
cosmic rain
#

What are we designers?

late lion
#

I would get rid of the Event in InvokeEvent to make it more readable. Then new fits into the sentence better:

EventBus.Invoke(new TimerPauseEvent(pauseTimeLeft));
#

(and remove the nested class)

wintry crescent
#

I like my systems to be nice and pretty black boxes from the outside, and when you go inside you're hit with a wall of comments that explain everything

late lion
#

"EventBus, invoke a new timer pause event"

wintry crescent
#

xd

cold parrot
wintry crescent
late lion
wintry crescent
#

it's a mixture of multiple systems, old and new

#

gotta love old code, don't we

cosmic rain
#

Maybe focus on refactoring it then, instead of wasting time on impossible syntax sugar.

late lion
#

Does it have to be combined into the same class?

wintry crescent
#

nope, we need the other functionality

wintry crescent
cosmic rain
#

Refactoring is intended to keep the other functionality.

latent latch
#

EventBus.Invoke(TimerPauseEvent.Instantiate(pauseTimeLeft));
There, got rid of new

wintry crescent
#

you can listen for events and procedures and you can invoke events and commands
commands convert themselves into a procedure list, and procedures have logic inside them which events dont, but can be listened for just like events

cosmic rain
wintry crescent
#

I'm not gonna modify the whole project to not rely on that, that's not my task

#

my task was to un...screwup the old system and I did, it's cleaner now and supports normal events

cold parrot
#

โ€œAbstractions from hell and other storiesโ€

wintry crescent
#

oh come on it's not that bad XD

cosmic rain
cold parrot
#

Hell is the best place ever until you get out

late lion
wintry crescent
cold parrot
wintry crescent
late lion
#

I don't see the problem with the new keyword in this context. I like to think of my events as payloads and that I'm constructing it as a whole before passing it along. I prefer that over thinking of events as a set of parameters.

quick owl
#

I am following a tutorial and Im wondering if this is a new handler of unity's api
I could not find its corresponding api page so if anybody knows what this is or if they know a page where this handler is explained it would be great help!

steady bobcat
placid summit
#

anyone using binary json? It is deprecated in the newtonsoft package Unity provides and a separate one had been created but damned if I can find the way to use it once added as a dll. I think BsonWriter became BsonDataWriter?

trim schooner
#

It's green, so it exists - though may be obselete/ deprecated

#

Just looked - it's for visual scripting

placid summit
#

unfortunately does not serialize in quite same way it seems

#

hit a self referencing loop

cold parrot
placid summit
cold parrot
#

if you need speed, you should look into message pack or protobuf

placid summit
placid summit
zinc plover
#

Quick question that maybe someone has some experience with: I'm wondering whether it is more performant to construct a new gameobject from scratch in code, adding all components through code, or to set up a prefab with the base components, instantiate that prefab, and then change all the values. This is in the context of creating gameobjects with generated meshes.

#

I doubt there will be a big difference but maybe someone can weigh in

placid summit
#

but if you want specific types of objects with other components in some cases - use prefabs

#

You can attach a 'root'/main component that pre-references a bunch of others on a prefab to make post-creation easier

cold parrot
zinc plover
#

well my objects are always the same, and the code is just

var myComp = new GameObject().AddComponent<MyComponent>()
myObj.AddComponent<MeshRenderer>()
var meshFilter = myObj.AddComponent<MeshFilter>()
var meshCollider = myObj.AddComponent<MeshFilter>()
// and then setting some object specific mesh and collider settings
placid summit
#

yeah I do that a lot - no issue, dunno of difference with using a prefab

cold parrot
placid summit
cold parrot
#

i would say gameobject instantiation is inherently so incredibly inefficient that it doesn't matter

#

your goal should be reusing objects and not creating them after startup of the scene if performance is your goal

placid summit
#

ah yes true - I myself pool when speed an issue

zinc plover
#

Not an option for procedural generation (except pools ofc)

cold parrot
placid summit
cold parrot
#

you may need to modify vertex position, but you would potentially not need to make a new mesh... but that depends, if you are making a dungeon, you should proc-gen that from a set of reusable parts.

#

also mind you that meshes are a bit tricky to proc-gen, there are a lot of hidden inefficiencies and potentials for memory leaks that dwarf the gameobject creation/instantiation costs.

zinc plover
zinc plover
#

but i was just looking at my gameobject creation code and wondering if I could optimize that

#

pooling is probably the best option for more optimization

cold parrot
#

or use entities ๐Ÿ˜„

zinc plover
zinc plover
#

something like DrawInstancedPrimitives

#

but you might mean something else?

latent latch
#

compute shader pretty good at that stuff

#

if not jobs

cold parrot
zinc plover
#

Definitely true, should be doable though

cold parrot
#

I would rather use entities than make a custom renderer, since entities gives you a lot of prebuilt things that you would need to DIY, and the end result will probably be better with entities

zinc plover
#

I honestly doubt the difference would be very impressive

#

even compared to just using straight gameobjects

#

with classic meshrenderers

cold parrot
#

depends, you can do impressive stuff with jobs

#

entities just removes the gameobject overhead but keeps stuff on the cpu.

#

entities without jobs don't make much (10x or more) of a difference for performance

zinc plover
#

thing is, I'm not ever really updating the chunk objects after they've been generated, so any performance gains would wholly depend on whether rendering data on entities is faster than rendering classic meshrenderers

cold parrot
#

with jobs you can get to 100 - 1000x depending on what you are doing, certainly in the area of mesh proc-gen.

zinc plover
cold parrot
zinc plover
#

mesh rendering is pretty optimized i think

cold parrot
# zinc plover mesh rendering is pretty optimized i think

yes and no, its fine for regular objects, but when it comes to "massive amounts of objects" the bottleneck is the calculation of the transform matrix for these objects, and there you would probably want to use jobs+entities or compute-shaders

zinc plover
#

yeah true

cold parrot
#

but many of these cases can just be delegated to a vfx graph

#

its certainly a complicated setup once you need that.

#

there is also a neat asset that helps with creating custom GPU based instancing renderers (GPU instancer)

zinc plover
#

I'm currently rendering 961 chunks (2-3M tris after culling) at like 200fps on an rtx 2070super

#

oh wait it's only 441 chunks

#

bumped it down because i made the chunks bigger

cold parrot
#

those numbers don't mean much ๐Ÿ˜„

zinc plover
#

and there is a TON of optimization left

#

like lods

cold parrot
#

ideally you want the terrain/background rendering to be sub 1ms

#

there is too much stuff to calculate in a game to waste CPU/GPU on the background

zinc plover
#

precisely because its spread between cpu and gpu and also mostly internal

cold parrot
#

not really, you can use feature toggles and check how much the gains are

zinc plover
#

fair enough

cold parrot
#

its a bit like stabbing in a black box

zinc plover
#

yea lol

cold parrot
#

you gotta have a plan and know why it works

#

i would aim for making stuff that is optimizable later, ie. make sure you don't block your path by silly early decisions.

zinc plover
#

im honestly not sure I can get unity to render this at higher speeds than 3-4ms per frame

cold parrot
#

but i would not optimize unless its absolutely neccessary

zinc plover
#

never seen framerates higher than that in unity

#

and I've easily gotten <1ms in custom renderer experiments ive made

#

in c++

cold parrot
#

its mainly spent on optimizing what comes after

zinc plover
#

yeah

#

convenience tradeoff

cold parrot
#

not convenience

#

its what a modern render pipeline needs to do to be performant

#

it does not scale linearly

#

like BIRP did

zinc plover
#

but also to be able to handle anything you throw at it

#

you can easily optimize a renderer for a very specific scenario to be way faster than that

#

but it's only going to be able to render your very specific thing

cold parrot
#

yes, unity's SRPs are aimed at optimizing dynamic scenes (moving camera, LOD, object activations etc.)

#

the more visual fidelity you need, the more you need to make your scenes static.

storm sleet
#

I am having an issue with order of execution maybe someone could tip me whats wrong, in short i have a monobehaviour that is merely there to fetch some resources and create some default models, i added it to the custom order script list to execute before default time, but then in my logs i have a script that needs one of this default models coming before the log on the priority script. this is all happening in edit mode

cold parrot
#

build your systems such that ordering is either explicitly expressed in code (by calling methods in order) or irrelevant.

storm sleet
#

i dont understand why.. i need this script to be executed before anything else

storm sleet
#

i am using awake

cold parrot
cold parrot
storm sleet
#

the default model generation in on awake, the log that is coming before is on another monobehaviour but its a model as public field, so its generated by the inspector

fleet gorge
#

Start an ienumerator that waits until the stuff is ready?

storm sleet
#

btw the cinemachine is there automatically when i apply changes it comes to -1 for some reason i just added the defaults as the 1st before default time

#
public MyModel()
{
    Debug.Log("Model initialized");
}
[ExecuteInEditMode]
public class MyMonobehaviour : MonoBehaviour
{
    public MyModel myModel = new();
}
[ExecuteInEditMode]
public class Defaults : MonoBehaviour
{
   void Awake()
   {
      Debug.Log("Defaults");
   }
}
quick owl
#

does the gameobject being active or not effect the Find() function?
I named the gameobject correctly yet it says its unassigned

plucky inlet
storm sleet
quick owl
#

ty

#

i will visit the api next time before asking

plucky inlet
#

this can give you a workaround if you got acomponent to search for. But direct reference is always better than using find

storm sleet
wintry crescent
#

Is there a reason why setting a 2dtexture on an unlit shader (on a canvas graphic) works normally, but setting a 2dtexture on a canvas shader results in what appears to be the topleft pixel filling the entire graphic?

#

the only difference is the type of shader (unlit/canvas) in shadergraph

plucky inlet
wintry crescent
#

texture is set via material.SetTexture

#

it is a texture2d I generate during runtime

storm sleet
latent latch
#

oh huh there's actual canvas shaders

wintry crescent
#

it's unity 6 specific thing

plucky inlet
wintry crescent
#

it works if I set it to unlit, but masking breaks

latent latch
#

The normal canvas shader is basically just stencil stuff so what are you trying to even do with this

#

probably better off just editing that directly

wintry crescent
#

in a way that works on unlit material

#

pretty straightforward

#

I just want to display a texture on my custom shader

#

by setting it via code

plucky inlet
#

Did you try to expose the texture as property and assign that to the basecolor?

#

For me it sounds like you are missing the UV distribution part somewhere

wintry crescent
#

it works on unlit

#

that multiply goes pretty much directly to the color value in fragment shader

plucky inlet
#

this works for me in UI

plucky inlet
wintry crescent
#

what I posted is the entirety of the color in fragment

wintry crescent
#

empty I mean

wintry crescent
#

I'm on newest unity 6

latent latch
#

Expand it with the down arrow on the node

#

also you got built-in targeted if that matters

plucky inlet
#

did you create it via this?

latent latch
#

oh wait yeah that node looking different

wintry crescent
#

I think that was the pre unity 6 node

#

I tried adding a new one and it looks like yours

latent latch
#

I know that built-in shader graph was included a little later so maybe they just updated it

#

I'm surprised it's still supported

wintry crescent
#

it works kinda, but the UV seems completely screwed up

plucky inlet
wintry crescent
#

expectation vs reality, assigned texture vs displayed

cold parrot
# storm sleet does it make sense?

the ctor on MyModel() is called immediately on load of MyMonobehaviour, before any Awake, if you want to have it run in Awake you need to call the new() in Awake, not as part of the field declaration. This has nothing to do with execution order at that point.

fluid siren
#
 private void Update()
 {


     // player jump
     if (PlayerJump.triggered && isGrounded)
     {
         Debug.LogWarning("jump is working ");

         Rigidbody2D.AddForce(Vector2.up * JumpHight, ForceMode2D.Force);

     }

     //player attack 
     if (PlayerAttack.triggered && isGrounded)

     {

         Debug.LogWarning("attack button is working ");
         Utility.connection.ChangeAnimationState(animator, Player_State.Attack.ToString());

     }


 }

am trying to make the player jump , but when it jump , he is too fast almost like he is teleporting , i try to change the mass and gravity , but didn't work

plucky inlet
#

Try to use impulse instead of force

fluid siren
fossil obsidian
#

I'm trying to optimize the inputs from my game, and I managed to learn the basics from the Input System but all the tutorials I see still uses Update() to detect the inputs, which is exactly what I dont want to use

vagrant blade
#

The original input system uses Update to poll for inputs. If you don't want that, you can use the current input system that uses events.

fossil obsidian
#

I'm using the new system but still

fossil obsidian
#

Do something that runs without taking that much from the device, and running an input processing method every single frame isnt that good.

heady iris
#

Checking inputs every frame is completely normal

#

That's what the new input system is doing internally anyway

#

Do you actually have a problem right now?

fossil obsidian
#

sometimes the fps decreases by 3 or 4, what wasnt supposed to be normal for the amount of features it has for now, and as its 2d

warm cobalt
#

is there a callback for once the asset database is done refreshing? or just any callback thatโ€™s called every time any asset is imported?

fossil obsidian
#

wdym

warm cobalt
# fossil obsidian wdym

I think I was descriptive enough

when literally any asset of any kind that unity needs to handle importing, ie when the progress bar comes up after importing an asset, Iโ€™m looking for a callback for after itโ€™s done doing that

#

so if I import an audio file for example, once itโ€™s done importing it I want to run some code directly after that

fossil obsidian
#

in this case, i think not

heady iris
heady iris
#

but it doesn't have callbacks for database refreshes

fossil obsidian
warm cobalt
#

nvm I think I found something

heady iris
warm cobalt
#

Iโ€™ll give the asset post processor a shot

heady iris
#

but this would call your code before the import is over

#

you'd get the call right before the import finishes (as postprocessors are running)

warm cobalt
#

good enough for my case

heady iris
#

I was talking to Zweronz there.

heady iris
#

If your framerate is dropping whilst you perform an action, then the issue is probably with the action itself

#

not with how you're receiving input

storm sleet
pallid leaf
#

Hi everyone,

Does anyone know if this works: PrefabUtility.GetCorrespondingObjectFromOriginalSource(GameObject)?

I'm trying to get the prefab of an instance object in my scene (Editor only). I want to save the prefab in a ScriptableObject. I've got two buttons, one for loading the object and the other for saving it, allowing me to configure some level data and save it.

However, I can't figure out how to get a prefab from its instance and save it in a ScriptableObject.

Can anyone help? Thanks in advance.

Edit : I think i've got something... PrefabUtility.InstantiatePrefab() And not Instantiate()...

rigid island
steady bobcat
latent latch
#

these freaking methods names rofl

heady iris
#

they're quite wordy

#

I find that entire chunk of the editor to be..kind of spooky?

astral nexus
#

Hello, I'm seeking for an advice with implementation of old RE-style fixed camera system. I've made one with trigger zones, but I don't like this solution, because trigger colliders will overlap sometimes and make it a bit convoluted (or I did it wrong, dunno).
Any ideas how to do it more properly without constant checking is player in view/zone? I'm using cinemachine ofc.

heady iris
#

If you switch to a zone's camera when you enter it, overlapping zones will behave decently

rigid island
#

takes a bit of tweaking but wayyyy better than using triggers

heady iris
#

ah, neat!

astral nexus
heady iris
#

That is very much wrong.

#

Cinemachine Cameras do not render anything

#

All they do is tell the real camera where to go

rigid island
#

@astral nexus yeah doubt thats true. all its doing is switching cams to which one Main Camera renders

heady iris
#

It is true that all of the cameras are doing their shot-quality evaluations

#

that's a given

mortal needle
#

Will setting enabled to true call OnEnable() and setting it to false call OnDisable()?

heady iris
#

Yes, the messages get sent immediately

#

Note that if an object is deactivated, the behaviours on it will be treated as disabled

#

The messages get sent if isActiveAndEnabled changes.

astral nexus
#

Oki, thanks! Will try this ClearShot camera thing

rigid island
#

yeah def! give it a try. Its pretty good when i used and also made a RE style game myself

#

some areas need tweaking but you can get really good results

heady iris
#

at that point, though, you'd probably just deactivate entire chunks of the world (or unload a scene)

teal bramble
#

I need help. I added First Person Controller Asset to my Unity project as player controller. I wanted to make a cut scene and it works fine.In cutscene I disable the player game object totally(thePlayer.SetActive(false)). After the cutscene finishes I do thePlayer.SetActive(true) and player won't stop moving until I make an input(W, A, S or D). Can anyone help?

leaden ice
raven bobcat
#

So I try to follow this tut.
https://www.youtube.com/watch?v=nSDhT6mxF8w&list=PLJWSdH2kAe_Ij7d7ZFR2NIW8QCJE74CyT&index=4
When I finished the vedio, I got an error that say: " NullReferenceException: Object reference not set to an instance of an object" on line 14. I check if I were missing a sprite, but it didn't seem like the issue.
The game still runs, but the error annoys me a lot. How do I fix it?

In this video we will be updating our #unity3D inventory system's graphics to use a 3rd person character controller and cinemachine!

Source Code: https://github.com/sniffle6/Scriptable-Object-Inventory

If you like this channel, or just Unity in general, consider joining my Discord at: https://discord.gg/5yj4Ecp

*******************************...

โ–ถ Play video
teal bramble
leaden ice
leaden ice
tawny elkBOT
raven bobcat
#

Hum...Okay I fixed it. I don't know why, but when I deleted the Apple and drag it from the prefab again. The error disappear.

full plover
#

how exactly would you go about character customization/clothing options for a 3D game? I have the model prepared, with (for example) 10 hair options, and theyโ€™re all just be parented to the head in the rig, then would I just make it to where all the meshes they arenโ€™t using with to be invisible? I feel like thatโ€™s self explanatory but then Iโ€™d need to do the same with every armour option, then the player would be running around with tons and tons of invisible meshes? I feel like thereโ€™s a more optimized way?

teal bramble
#


using StarterAssets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CutScene1 : MonoBehaviour
{
    public GameObject thePlayer;
    public GameObject cutSceneCam;
    public Transform transformPlayer;
    private CharacterController charController;

    private float moveSpeed = 5f;
    Quaternion rotacija = Quaternion.Euler(0f, -90f, 0f);

    private void Start()
    {
        transformPlayer = thePlayer.GetComponent<Transform>();
        charController = thePlayer.GetComponent<CharacterController>();
    }

    private void OnTriggerEnter(Collider other)
    {
        this.gameObject.GetComponent<BoxCollider>().enabled = false;

        cutSceneCam.SetActive(true);
        thePlayer.SetActive(false);
        thePlayer.transform.position = new Vector3(816f, 147f, 280f);
        thePlayer.transform.rotation = rotacija;

        StartCoroutine(FinishCut());
    }

    IEnumerator FinishCut()
    {
        yield return new WaitForSeconds(3);

        cutSceneCam.SetActive(false);
        thePlayer.SetActive(true);



    }
}

rigid island
teal bramble
leaden ice
teal bramble
livid olive
#

Hey all I'm trying to place a unit in a grid space where the mouse position currently is. For some reason unity is placing it based on the global position and not the local position when the game object is a child of the grid. Code is in this pasebin : https://paste.mod.gg/hvavkejchdex/0

#

Weird thing is the Debug.log is placing the unit Where I want it to be. But for some reason when its instantiated, it instead utilizes it as a gloabal position instead.

latent latch
#

So you're changing a world into a cell position (Vector3Int), but then instantiating it using that Vector3Int as a global position

livid olive
latent latch
#

Right, if you want the pivot of the cell in world space you need to change that cell into a world position

livid olive
#

Right but in this case I'm converting mouse position to a cell on a grid.

#

I want those ints to show me the closest cell position to the mouse cursor.

latent latch
#

Which you are getting I believe here, but the problem is that you want to instantiate it directly on the pivot right

livid olive
#

I believe so

#

So i would need to convert it back

#

huh. I'll give it a shot.

latent latch
#

I mean you know the world value already from the pointer

#

just I assume you want to align it now

leaden ice
#

so that's the script where the issue would be

#

seems pretty clear that it's probably just storing stale input data since you disabled it

astral nexus
#

maybe I'm stupid, but how can I change ClearShot camera fields in cinemachine through script? Like default target, etc.
code on the screenshot is throwing null reference, even when field is set in the inspector
am I missing something?

latent latch
#

chances are your find methods isn't finding

astral nexus
#

I've tried for this pure possibility as a test: using _target serialized field before and it's doesn't work either

astral nexus
#

like I don't know why, lol, because funny enough - default target and other stuff in clear shot camera is set by it (I've checked), but it still throwing error there like if if ClearShotCamera object is null

leaden ice
teal bramble
#

Thanks

midnight hazel
#

I'm experiencing an error with a gameObject that has an OnMouseDown and OnMouseDrag on it. When I use the button that is over the gameobject it activates the mouse handlers. How Do I stop this from happening? I've seen some outdated solutions but I'm not sure what is current practice.

leaden ice
heady iris
#

isn't that completely unrelated

leaden ice
#

And you'll get that fix for free

wary coyote
#

I am working on an implementation of Cubical Marching Squares and using a sphere as my test geo this is the earliest result I've gotten to run without console errors.
What is most likely to be faulty to produce a result like this? My VertexOffset, EdgeConnection, EdgeTable, TriTable lookup tables? Or the code making use of the tables?

I admit I am out of my element trying to render voxel isosurface type stuff so I'm not sure where to start to determine why it looks the way it does

The corner vertex is because its treating the very first vertex as 'inside' even when its not which I can fix, but the bridging I am guessing is because of bad lookup tables?

heady iris
leaden ice
#

i.e. if you use IPointerDownHandler instead of OnMouseDown

heady iris
#

it has nothing to do with UI input

leaden ice
#

and you will get the UI blocking behavior for free

#

it works for both UI and physics objects

heady iris
#

Oh, I see

#

I thought you said to use OnMouseDown

leaden ice
#

No, I'm saying to move away from it.

heady iris
#

Ah, I see -- you attach a Physics Raycaster to the camera

#

Neat. I had no clue about that.

#

I've not done very much with clicking on things in the world

#

beyond very basic "click -> raycast" stuff

#

That makes sense. Everything goes through the EventSystem, which understands if the UI is in the way

heady iris
livid olive
kind nymph
#

ok completely unrelated problem to the one before (Which i've since fixed), I'm getting a NRE when OnCollisionEnter2D is being called and I have no idea why, I was thinking maybe it could be something to do with the GetComponent<EnemyStats>() or something (short and brief becuase its just a null reference exception its probably something stupid tbh)

NullReferenceException: Object reference not set to an instance of an object
ProjectileMove.OnCollisionEnter2D (UnityEngine.Collision2D other) (at Assets/Resources/Scripts/ProjectileMove.cs:6)

https://paste.mod.gg/pmwewtllgauy/0

somber nacelle
#

which is line 72

latent latch
#

The IPointer interfaces also take into account of canvas ordering so elements ordered earlier will block raycasting. Sorting is a pain in the butt otherwise doing it by graphics raycasting

kind nymph
kind nymph
somber nacelle
#

then yes, stats is null which means the object that was collided with does not have an EnemyStats component

kind nymph
#

oh

somber nacelle
#

you can use TryGetComponent to check if it has the component and do the GetComponent all in one line. you'll want to do the same for the PlayerStats component in the else if as well

kind nymph
heady iris
#

TryGetComponent is great.

#

It's not much smaller than a GetComponent followed by an if(result), but it's very...expressive?

#

it's obvious what you're doing

#

(there is also a nominal performance benefit in the editor: it doesn't create an invalid unity object if it fails)

kind nymph
#

well now the fun part is figuring out why it thinks the collided object doesnt have an EnemyStats component when I have checked numerous times and it clearly does

heady iris
#

I'm unclear how this works in 2D physics, but in 3D physics, Collision.gameObject is the object with the Rigidbody on it if one is involved

#

The Collision2D documentation doesn't specify

#

...well, Collision also doesn't really make it explicit

#

If you want the object with the collider on it, access the collider field and then get its game object

kind nymph
#

ill try that first then

somber nacelle
#

also keep in mind that OnCollisionEnter would also be called for collisions with scene geometry (assuming that this object has a rigidbody)

heady iris
#

Either way, you should check what object you're actually getting

#

It doesn't matter what you think you're receiving.

kind nymph
#

Doing an if statement with CompareTag() seems to have fixed the issue

#

thanks guys ๐Ÿ‘

heady iris
#

you can also just bail out if TryGetComponent fails

#
if (!hit.gameObject.TryGetComponent(out Foo foo))
  return;

foo.Bar();
kind nymph
heady iris
#

It does not.

kind nymph
#

huh

heady iris
#

Trying to use the result will cause one.

#

TryGetComponent returns a bool that indicates if the component was found

kind nymph
heady iris
#

oh

#

just...don't do that

#

if the component doesn't exist, you didn't hit an enemy

#

you hit something else

kind nymph
heady iris
#

most of my collision messages look something like this

#
if (!hit.collider.gameObject.TryGetComponent(out ImportantComponent thing))
  return;

thing.Whatever();
#

Tags are okay, but they fall apart if an object can represent more than one kind of thing

#

what if you can shoot it AND pick it up?

dense pasture
#

is there something im missing with these colliders thats not triggering the script?

heady iris
#

There's no rigidbody involved, so the colliders on the ship won't do anything

dense pasture
#

player controller doesn't trigger collisions? it seems to stop movement normally

heady iris
#

That's very different.

#

in fact, moving a CharacterController into a wall doesn't cause a collision at all

kind nymph
dense pasture
#

why does it stop it from moving through it?

heady iris
#

It just looks at the environment and moves accordingly

#

the CharacterController can cause collision and trigger messages in some situations

dense pasture
#

the main issue i'm running into is when using the evasion skill it phases through the wall

heady iris
#

(when things hit it)

dense pasture
#

but i'm using smoothdamp for that

somber nacelle
dense pasture
#

i see

heady iris
#

You can, indeed, get a message when a CharacterController tries to go through a solid collider

heady iris
#

Bumping into a collider is normal behavior

#

Errors should be displayed (and exceptions should be thrown) when you get into an unexpected situation

dense pasture
#

does using smoothdamp on the transform.position just not trigger collisions at all?

kind nymph
heady iris
#

That completely sidesteps everything!

#

the CharacterController has no say, and the physics system has no clue what's going on

dense pasture
#

ah

heady iris
#

You can use SmoothDamp to move the current position towards a target

#

and then use that change to tell the CC to move

#
Vector3 desire = Vector3.SmoothDamp(transform.position, target, ref velocity, 1f);
Vector3 move = desire - transform.position;
controller.Move(move);

e.g.

dense pasture
#

its really just down to that the wall doesn't stop the evasion skill

#

ah thats what i was hoping for. ok cool

#

yep that does it!

dense pasture
heady iris
#

"static" meaning that there isn't a rigidbody involved; this has nothing to do with the Static flags of game objects

dense pasture
#

yeah

heady iris
#

If you're totally ignoring physics, then you'll probably want to use a spherecast to sweep out the path of the ball

dense pasture
#

i can't just have the boundaries trigger OnCollision off a sphere collider on the ball?

#

for most purposes it will travel in a set direction and velocity until it impacts a wall, enemy or the player paddle

heady iris
#

But there's no physics happening here

#

You're just moving the ball around

#

The physics system isn't simulating the motion of the ball and finding where it hits colliders

#

That's the issue.

dense pasture
#

i'm not super familiar with the whole toolkit

heady iris
#

A spherecast can tell you if any colliders get in the way of a sphere moving from one point to another

lucid brook
#

I'm having some issues when it comes to moving my player up and down slopes. My player hovers slightly off the ground to make moving over small bumps smoother but as soon as I walk up a slope the player gets pushed into the slope instead of neatly going up it. Even though I use Vector3.ProjectOnPlane() the DrawLine even shows the normal of the force correctly, but the player is still pushed against the slope instead of up it. https://gyazo.com/eda0309a9fd16b23422e9c8de943afd5

Relevant PlayerHover Code ```C#
onSlope = Vector3.Angle(Vector3.up, groundHit.normal) != 0;
slopeAngle = groundHit.normal;

`Relevant PlayerMovement Code` ```C#
if (playerHover.onSlope)
{
    velocityChange = Vector3.ProjectOnPlane(velocityChange, playerHover.slopeAngle);
    Debug.DrawLine(this.transform.position, this.transform.position + velocityChange.normalized, Color.red, 5f);
}

ForceMode forceMode = isGrounded ? ForceMode.VelocityChange : ForceMode.Force;

rigidBody.AddForce(velocityChange, forceMode);
bronze rampart
#

Sort of off topic but does anybody here know if the .vsidx visual studio generates for indexing new files is safe to ignore in version control?

I just want to ignore them when doing backups and probably in VC as well all these small files tend to add up and slow down transfer rates for my ancient nas. i cant see any reason it would cause a problem but id really rather not fuck up my VC

heady iris
#

they're index files created by VS to speed up searches

#

sounds safe to ignore to me

bronze rampart
#

yeah i mentioned that... do you know if thatl cause an error when searching if the vsidx is missing

heady iris
#

I presume Visual Studio looks for an index file

#

and if one exists, it gets used

somber nacelle
#

isn't that normally in the .vs folder which should be ignored? ๐Ÿค”

bronze rampart
#

yeah. good call thought i was ignoring that already ty

leaden bluff
#

Hi hi!
I am having my brain melted by the following problem. I made a state machine for my game, and the transitions between the states are triggered due to some signals. For example, Atack1(State) -> AnimationEnded(Signal) -> Idle(State).

I added something I called TransitionFilters, that work to block out the transition between states (or allow them).
Now, the real problem: These TransitionFilters, are all classes that inherit from an ITransitionFilter (an interface), and I want to be able to create these transition filters on a scriptableObject. But for that, I wanted to have some kind of drop-down to select the type of TransitionFilter I want to create, like the added image.

Currently, every type of filter has an enum value used to have a dropdown in the inspector:

public enum TransitionFilterType
    {
        DF_NULL,
        DF_IS_MOVING,
        DF_FROMTOFRAME,
        DF_UNTILFRAME,
        RS_MODECHANGE
    }

But I don't know how to map these enums, to their corresponding class withouth it being a headache. Currently I am using a switch case:

 public static StateTransitionFilterSRL BuildStateTransitionFilterSRL(TransitionFilterType _type, int _frameLength){
    switch (_type)
    {
        case TransitionFilterType.DF_IS_MOVING:
            return new IsMovingFilterSRL();
        case TransitionFilterType.DF_UNTILFRAME:
            return new UntilFrameFilterSRL();
        case TransitionFilterType.DF_FROMTOFRAME:
            return new FromToFramesTransitionSRL();
    }
}

But it's gonna get ugly real fast with each type of filter

#

Basically the question lies in:
How can I expose on the inspector all the child classes that inherit from ITransitionFilter, and map said exposed variable to the proper class/constructor of the corresponding class?

somber nacelle
quartz folio
#

Note that I'm using Odin in the current project I'm working with so I've not had time to make sure that package is functioning well, but it should handle simple cases easily.
There are many different type dropdown packages for SerializeReference though, so each would be a harmless drop in replacement for one another if one doesn't work

somber nacelle
#

i haven't had any issues with it in 6, other than when some other type i had no control over forced the inspector to use IMGUI and i needed to grab the editor patching dll

quartz folio
#

That's good to hear

#

I have a bunch of random packages that I've not touched for years that I'd love to nuke, and some that haven't been touched but are very stable and will stick around forever

#

One day I'll get time to set a load to ReadOnly and pretend they never existed

leaden bluff
#

@somber nacelle I am a dum dum and never played around with SerializableReference, but after about 2 hrs I came to the realization that Odin has been hand-holding me. So... I somehow already had a kind-of serializableReferenceDropdown.

Now, it's not the exact solution I wanted, but I can instance an object of the desired class, and edit the values using a button (I didn't mention it but I wanted to have the constructors for the different TransitionFilters with some parameters, but I can always just instance it and modify it post).

So... yeah, apparently I had all the tools I needed. Only tiny issue I have right now is that the "label" is bloody long lol

quartz folio
leaden bluff
vital vortex
#

!code

tawny elkBOT
next osprey
#

Hi im having an issue with movement. My character always moves along the cardinal directions, but I want my character to move based on the direction theyre facing(1st person camera). https://hastebin.skyra.pw/exapayapar.pgsql

leaden ice
#

<@&502884371011731486> AI bot^

quartz folio
#

!softban 775082234507427890 bot spam

tawny elkBOT
#

dynoSuccess .remmy was softbanned.

next osprey
somber nacelle
#

that should work just fine assuming the rigidbody is actually being rotated to match the camera's rotation

#

although using ForceMode.Impulse for regular movement is suspect ๐Ÿค”

leaden ice
#

Yeah I would say your rb is not actually rotating if this doesn't work

#

And yeah deltaTime with the force is wrong

somber nacelle
#

ah yeah that too

leaden ice
#

But that's cancelling out impulse (sort of)

heady iris
quartz folio
#

lol

heady iris
#

i'll have to figure it out again tomorrow

#

i hope it wasn't just "i don't like how it uses two rows"

next osprey
#

honestly, ive been replacing everything to try and brute force it, so some things are left over from those experiments. I figured the rb might not have been rotating, but when i tried changing the rb's rotation, it didnt work so i figured i might as well ask.

#

should " rigidbody.rotation = camera.transform.rotation;" in the first line work?

leaden ice
quartz folio
next osprey
#

here's the input settings, that could also maybe causing the issue

next osprey
#

I tried changing the rb rotation to match the player's last night, didnt work. I added the new line 15mins ago, didnt work. I spent those 15 min changing and testing different debug logs, and now it works. Character flies now, but it works ๐Ÿ’€

#

oh it was the " * Time.deltaTime" change into " * Time.fixedTime". ๐Ÿ‘

leaden ice
full plover
calm echo
languid hound
#

Is there a way to get a point on a collider but keep said point on the outside?

#

ClosestPoint is near what I want but it's not quite because if the point it inside then it just returns the point

latent latch
#

Is this a trigger collider?

languid hound
#

I think I might just have to do something hacky like multiplying the direction from the collider to the point by a huge number then getting the closest point to that

#

Nah normal collider

steady bobcat
#

primitive or mesh?

languid hound
#

Primitive right now but at some point I want to support mesh

steady bobcat
#

cus for sphere or cube its simple but for mesh the only way i can think of is find the closest edge (2 verts) and project onto the line between them ๐Ÿค”

#

im thinking 2d here derp, not sure what works for 3d

languid hound
#

Yeah it's a bit of a nightmare I'm a bit upset Unity doesn't have something for this considering it has a lot of usecases

latent latch
#

usually need some type of intersection if you want that accuracy

west lotus
languid hound
#

Tbf that works in my favour it's a climbing game so the hand is gonna have some form of radius

#

I'll give it a try. Thank you very much guys!!

wheat spruce
#

I'm not too sure what the name of this issue might be called, but notice in the video how the object rotates in one direction then immediately flips to the opposite direction. The problem seems to be like the image shows, where the joystick is on one side, but once the joystick crosses over a 180-degree angle, the rotation immediately starts to turn in the opposite way.

The code responsible for that is here:

float currentAngle = Mathf.DeltaAngle(0f, transform.eulerAngles.z); // current angle with range [-180, 180]
float targetAngle = -Mathf.Atan2(targetDirection.x, targetDirection.y) * Mathf.Rad2Deg;
// the two angles, to calculate a difference
float angleDifference = Mathf.DeltaAngle(currentAngle, targetAngle);

RBody.angularVelocity = angleDifference;```Even though I get what the issue is, I dont really have an idea for how I'd fix it
pallid pollen
#

Hello, i am trying to create a development build for my project. It doesnt work and i get following error: System.BadImageFormatException: Format of the executable (.exe) or library (.dll) is invalid. at Mono.Cecil.PE.ImageReader.ReadImage()

if i make a non development build its works fine. Does anyone have any idea what the reason could be?

placid summit
hardy pasture
#

How to make a box editor like what we have on BoxCollider2D?
I'd like to create a game object in which I define a box similar to how I define box collider and then divide that box into regions like this:

#

This is for visualization and debugging. In this case this box would define the playing area for my game with regions inside it for AI to use. It's not a collider.

wheat spruce
placid summit
latent latch
#

My crappy fix to this is just remap the angle if you're not expecting negative value for a rotation

placid summit
#

then debug log what is coming out

latent latch
#

You can also use quaternions and just slerp it oh nm you're using rigidbodies

#
Quaternion currentRot = transform.rotation;
Quaternion targetRot = Quaternion.LookRotation(Vector3.forward, targetDir);
Quaternion delta = targetRot * Quaternion.Inverse(currentRot);```
That will ditch the trig stuff if you wanted
#

otherwise quaternion Angle and cross product probably

wheat spruce
#

eh, I'll worry about it later. I cant get it behaving any different

#

the movement is fine overall anyway, I'll just put it on my kanban board for later

left bear
#

GCHandle.Alloc == fixed() in unsafe burst function im i right?

cinder raft
#

"t:material shader:Universal Render Pipeline/Lit"

i want to search for materials that are lit , how can i do this in editor ?

#

this doesnt seem to work

deep stirrup
#

What's the best for performance way to get average color of render texture in MonoBehaviour script?

cosmic rain
#

It depends on if you're constrained by time or not. Like, is it fine to do that over several frames?

deep stirrup
deep stirrup
cosmic rain
#

Maybe with jobs and burst, but even then GPU solution would be faster probably

late lion
#

I don't know if HDRP keeps everything on the GPU or not. There might be some benefit of knowing what exposure level you have in script, so you can modify it further, add progressive adjustment, etc.

cosmic rain
#

Some custom engine I'm working on at work does several downscaling passes on the render target. In the end you have 1 pixel wide texture with the desired color. Then you can just read it on CPU if you really need to. Usually it's just used in other shaders.

deep stirrup
grim fjord
#
//Get random upgrades
int[] randomUpgrades = new int[4];
for (int i = 0; i < randomUpgrades.Length; i++)
{
    bool upgradeIsUnique = false;
    while (!upgradeIsUnique)
    //for (int j = 0; j < 4; j++)
    {
        //Get upgrade to set
        int numToSet = Random.Range(0, upgradeManager.GetComponent<UpgradesGeneral>().upgradeList.Count);

        //Check if upgrade has already been chosen
        upgradeIsUnique = true;
        for (int u = 0; u < randomUpgrades.Length; u++)
        {
            if (numToSet == randomUpgrades[u]) { upgradeIsUnique = false; }
        }
        if (upgradeIsUnique) { randomUpgrades[i] = numToSet; Debug.Log("Upgrade Is Unique"); }
    }
}

Must be a better way to do this than a for loop inside a while loop inside a for loop. Plus it's crashing due to an infinite loop. Any help appreciated, thanks in advance

chilly surge
#

Have a list of available upgrades, as well as a list of chosen upgrades. Every time you randomize one from the available list, remove it from the available list and add it to the chosen list.

grim fjord
grim fjord
leaden ice
#

Imagine a deck of cards. You shuffle it then just pull from the top as many as you need

grim fjord
oak salmon
#

Damn

#

Y'all are smart as hell

#

I feel dumb now ๐Ÿ˜ญ

steady bobcat
#

I either do a pool that i remove items from and re fill when empty (to avoid duplicates) or a single loop item swap.

late lion
eager fulcrum
#

Hey, so I have a simple setup,
One object has a rigidbody and collider2d, second object has only collider2d set to trigger.
When first object enters the area of the second collider it should trigger this

 private void OnTriggerEnter2D(Collider2D collision)
 {
     //do stuff
 }

but it doesn't, why?

grim fjord
eager fulcrum
#

on the one with rigidbody

leaden ice
#

Is it a Rigidbody or Rigidbody2D

eager fulcrum
#

2D

leaden ice
#

How do you know the code isn't running?

#

Did you put a log statement as the first statement?

eager fulcrum
#

yes I did

#

they are on the same, Default, layer

#

okay im just stupid... the second object had Collider and not Collider2D

grim fjord
# leaden ice Imagine a deck of cards. You shuffle it then just pull from the top as many as y...
//Get random upgrades
int upgradeCount = 4;
List<Upgrade> upgradesToChose = new List<Upgrade>();
upgradesToChose.AddRange(upgradeManager.GetComponent<UpgradesGeneral>().upgradeList);
List<Upgrade> upgradesChosen = new List<Upgrade>();
for (int i = 0; i < upgradeCount; i++)
{
    int upgradeToChose = Random.Range(0, upgradesToChose.Count);
    upgradesChosen.Add(upgradesToChose[upgradeToChose]);
    upgradesToChose.Remove(upgradesToChose[upgradeToChose]);
}

Don't think it's perfect but so much better now, thanks for the help guysss

midnight hazel
#

I'm refactoring my code to use IDragHandler instead of OnMouseDrag and am running into problems. old code : https://hastebin.skyra.pw/zoterepojo.csharp
new code : https://hastebin.skyra.pw/izovuwesed.csharp
The old code works just fine with some minor bugs in clicks with the ui going through. The new code I cannot even get to show debug logs. I have a Mesh collidger on the object I want to drage. I have a physics2d raycaster on the camera. I also have an event system setup. Could you please take a look and give me a resource to look at to get Idraghandler to work?

wheat cargo
#

Looking for feedback on this API design for drawing lines at runtime, this is an example of consuming code:

public class TestLines : MonoBehaviour
{
    private LineHandle _lineHandle;

    private void Start()
    {
        _lineHandle = LinesManager.AddLine(new float3(0, 0, 0), new float3(0, 1, 0), Color.cyan);
    }

    void Update()
    {
        float3 startPos = new float3(currentIndex, 0, 0);
        float3 endPos = new float3(currentIndex, 1, 0);

        if (currentIndex % 2 == 0)
        {
            _lineHandle.SetValues(startPos, endPos);
        }
        else
        {
            _lineHandle.SetValues(startPos, endPos, UnityEngine.Random.ColorHSV());
        }
        currentIndex++;
    }
}
storm sleet
#

in an editor script in edit mode, on OnInspectorGUI, i am not being able to save the state of my object, i am using:

serializedObject.Update();
serializedObject.ApplyModifiedProperties();

what am i missing?
btw i have a monobehaviour with some fields one of which is a [Serializable] model this is the object that is not being saved

heady iris
#

Calling Update() will discard any locally modified properties that have not yet been applied.

wheat cargo
heady iris
#

Update should be used if the original object has changed (i.e. you went and modified the C# object)

heady iris
#

I've always just constructed a new one every time ๐Ÿ˜ฌ

wheat cargo
heady iris
#

ooh, I see

#

I've mostly been writing EditorWindows as of late

#

I actually haven't written a custom editor in a while

storm sleet
#

i am not quite sure, but i had misunderstood the update function, i am revitalizing an old project so i am still getting acquainted

wheat cargo
#

But otherwise yes if you need to construct it in an editor window for example, you usually don't reconstruct every redraw

storm sleet
#

so yes, i am not constructing a new serialized object i am using the default

heady iris
heady iris
storm sleet
#

i tried removing the update but it didnt change anything really

heady iris
#

Share the entire script.

storm sleet
#

I have a "parts" array and when those parts change i will modify the object to accomodate the new(or remove a) part and then i add GUI for that part to edit some values, finally i apply the modified properties

wheat cargo
#

UI toolkit has less pitfalls in this regard in my opinion, only downside is if you are making an asset / package that you want to target older editor versions, but UI Toolkit has been in the editor for quite a few versions now

#

values just get bound and you don't have to really worry about calling those methods at all

storm sleet
# heady iris Share the entire script.

its long, complex but is as i said, i check for changes on the object i do some modifications on the object via code and add gui to the inspector, everything is working except that if i reload the scene the changes are not set

heady iris
#

"some modifications on the object via code" -- are you talking about the SerializedObject, or is this something else?

storm sleet
#

no i am talking about the model i mentioned

heady iris
heady iris
storm sleet
#

its not a prefab

#

there is no prefab

#

i have a component (monobehaviour) with a field that is a model serializable class, that field is not being saved, that is the object i am modifying along with the GUI of the component to reflect that model instance

steady bobcat
heady iris
#

We need to see what you're actually doing. I don't want to try to debug this via a game of 20 Questions

wheat cargo
storm sleet
#

its 300 lines i wont post it sorry, i apreciate your help but i wont share in this case since its generic issue not bound to one particular method

heady iris
#

Correct. Everything should Just Work, with no further fussing.

heady iris
#

We won't die.

#

!code

steady bobcat
tawny elkBOT
rigid island
limpid siren
#

I don't know in which channel to ask that,
WHY IS VSYNC TAKING 11MS?????

heady iris
#

because it's waiting for the appropriate moment to continue rendering

mellow sigil
#

That's the entire purpose of vsync. It fills up the remaining frame time so that fps stays constant.

limpid siren
#

huh, I never looked at it like that

#

so should I just not worry about it?

mellow sigil
#

If you want vsync then it's doing its job

wheat cargo
limpid siren
#

but I don't know how it would go on a lower end machine

limpid siren
wheat cargo
#

You can do it in code or the player settings

mellow sigil
#

I mean if you want 100% of frame time to be used by the game itself then disable vsync and let it run on max fps

limpid siren
rigid island
limpid siren
#

VSync Count?

#

well

rigid island
#

yes