#archived-code-general

1 messages Β· Page 447 of 1

wintry crescent
#

even on plain scriptableObject classes, any list of types deriving from IdentifiableScriptableObject results in the bug

#

can someone test if it's just me, or if the bug appears for other people too?

somber nacelle
#

you should test in an empty project and submit a bug report if you can reproduce it there

silent bolt
#

Hey i'm trying to use the new Input System for the first Time (i'm a full beginner). I followed a tutorial. But the Input System doesnt seem to recognize the Keys.

What i've done:
Add Player Controller Script to the Player.
Add Player Input to the Player.
Add ActionMap & set Default Map.

The PlayerController Script has:
float value for speed
Vector3 value for moveDirection
and takes a InputActionReference (which i put to Player/Move)

I set thte moveDirection value to public so i can see the values change. .but theres nothing happening.. did i do it completely wrong ?

leaden ice
#

these two approaches are completely unrelated

#

with InputActionReference you will need to Enable() the InputAction before it can be used

#

i.e. cs void Start() { move.action.Enable(); }

#

And it remains that your PlayerInput component here is useless and extraneous

#

you should either remove the PlayerInput component, or rewrite the code to use it instead of the InputActionReference

silent bolt
#

Oh okay.. thank you! I've followed this tutorial :

https://www.youtube.com/watch?v=ONlMEZs9Rgw&ab_channel=BiteMeGames

He's using both & it worked for his 2D controller.

I'll try to change the things you mentioned. Ty!

In previous videos, we've already talked about how we ditched Rewired in favor of Unity's new input system. In today's video, Thomas goes over the basics of the new input system, and how you can get started with it on your own.

Timestamps:
00:00 What's an input system?
00:28 Why not the old?
01:29 Setting up movement
09:47 Setting up actions
1...

β–Ά Play video
leaden ice
#

there is no reason to have the PlayerInput component with this approach

silent bolt
# leaden ice this tutorial is leading you astray

Yeah i'm currently followin the Unity Courses.. but Unity automaticly sets the Input System to the new One.. so i tought it would be great to learn the new input system to create the Prototype projects with the new system. As they show it with the old one

leaden ice
#

there might also be some weirdness with whatever version of the Input System he is using where the PlayerInput is serving one important function - which is enabling the inpuit asset.

naive swallow
#

The biggest problem with the Input System is that there's like twenty different ways to actually use the input map and no one seems to agree on the correct way

#

A lot of youtube tutorials are basically just repackages of other people's tutorials without actually taking the time to understand what they actually mean and you get mixed signals like this one

silent bolt
#

better way would be reading the unity docs.. probably.. right ?

rigid island
#

its just Polling, Events and Broadcast Messages

naive swallow
#
naive swallow
rigid island
silent bolt
#

put ty anyways! I'll try other ways to get to the goal.

mossy shard
#

Does anyone have a good force calculation for a throwable object in a 2d space?
I have tried some Impulses and setting the force with AddForce but it is a little odd..

leaden ice
#

what's the goal

#

the force calculation is as always: f = ma

silent bolt
#

Got it Working an easy way πŸ‘

mossy shard
leaden ice
rigid island
mossy shard
#

It looks glitchy at times and if i set the throw force at let's say 3 it goes into another universe (it means it goes too fast)

leaden ice
#

especially with Impulse

rigid island
vestal arch
#

did you set mass really low?

mossy shard
leaden ice
#

and you'll have to explain what "looks glitchy" means exactly if you want help with that part.

mossy shard
#

ONE

silent bolt
vestal arch
#

!code

tawny elkBOT
leaden ice
# mossy shard ONE

Ultimately - explain what you're actually trying to accomplish here, and show your code if you want better help

rigid island
leaden ice
#

that's super vague

#

show code. Explain what you want in more detail

silent bolt
rigid island
silent bolt
silent bolt
rigid island
mossy shard
#
 ///shoot(..) is being called ONLY once i press the ,,shootingKey"
    private void shoot(float straightness)
    {
        ///Direction of the mouse in corespondence to the world.
           Vector2 dir = directionToMouse();

            Vector3 position = new Vector3(playerObject.position.x, playerObject.position.y, 0);

            GameObject projectile = Instantiate(throwableObject, position, playerObject.rotation);

           Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();

         
          ///straightness is a value between 0 and 1 and it evals how fast does it go
           rb.linearVelocity = dir * getThrowForce(throwForce , rb) * straightness;
        
    }
#

not so long

#

getThrowForce returns throwForce

rigid island
leaden ice
silent bolt
leaden ice
# mossy shard changed it

well, settle on a single bit of code and what's going wrong with that single bit of code before asking us questions

#

And show the full script

#

there's too many variables here for us to know what's wrong

#

you have directionToMouse();, throwForce , getThrowForce(throwForce , rb) and straightness which are all influencing this thing

#

and we can't see any of them

mossy shard
#

And i don't think you would like me to send you 3 classes just to look for 2 variables, 😭

naive swallow
leaden ice
#

And as far as I can tell from this code, there is only one class involved

#

I would absolutely like you to send all the code

naive swallow
#

And what is the actual problem anyway? Did we ever get more detail than "is odd"

leaden ice
#

nope

mossy shard
#

better if i send my whole project? 😭

rigid island
#

a video would also be nice..

leaden ice
#

"odd" is completely not actionable

leaden ice
#

and show the code that was asked for

naive swallow
silent bolt
#

i guess his projectile is too fast .. as much i understood ?!

leaden ice
#

no

#

that doesn't make sense

rigid island
#

"is odd" doesn't explain that

leaden ice
#

if it's too fast, reduce the speed

#

too fast is not "odd"

naive swallow
#

Whatever magic sauce the getThrowForce function has should be less so

leaden ice
#

there could be magic sauce inside of getThrowForce or directionToMouse()

#

as well as the calculation of whatever throwForce is and straightness

silent bolt
#

try to divide you straightness by 10 if it defines the speed (as the comment shows)

compact pier
#

Guys I'm new heare where and what sld i start with ?

silent bolt
#

maybe send the values here of
dir
getThrowForce
straightness

rigid island
tawny elkBOT
#

:teacher: Unity Learn β†—

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

rigid island
compact pier
leaden ice
#

no

#

of course not

rigid island
#

lol

leaden ice
rigid island
#

they put it there "for fun"

compact pier
naive swallow
# compact pier 750!!!?? Daymmm

Yeah, it's a bit short, but it's meant to be just a brief getting started content, a jumping off point. You can find the rest later

vestal arch
#

learning everything is impossible

leaden ice
#

there's always more to learn

rigid island
#

start with the pathways then go from there

vestal arch
#

even if you learn everything that exists now, there will be new stuff coming out faster than you can learn it

silent bolt
compact pier
rigid island
#

dev is a never ending process of learning

compact pier
compact pier
#

But like it's soo complex

#

Sld i start from 2d or 3d!

silent bolt
#

Unreal Engine is harder to learn imo

rigid island
naive swallow
compact pier
vestal arch
#

you can never know everything
what you can do, is learn the fundamentals, then basic tasks, then get the skills to get more information/knowledge as you need it. you'll never know everything, but with the right skills and mindset, you'll be able to know everything you need

vestal arch
rigid island
#

once you learnt the basics it doesn't look as "Scary" or complicated

compact pier
vestal arch
#

neither is harder than the other, they're just a different set of skills

compact pier
rigid island
#

3D imo is easier but its just personal opinion

compact pier
#

So like in that 750 hours I'll learn the basics?

compact pier
rigid island
#

you are also meant to learn c# outside of the Unity learn site..

naive swallow
#

Learning isn't, like a binary switch. You don't go from "not learned" to "learned" in a discrete time span

rigid island
#

it has good stuff for c# relating to Unity but you still need to learn traditional c#

vestal arch
compact pier
rigid island
#

no

compact pier
naive swallow
vestal arch
vestal arch
silent bolt
compact pier
naive swallow
#

Best get learning

rigid island
#

if you know C++ then c# should be a cakewalk..

vestal arch
compact pier
compact pier
rigid island
#

C# is very similiar to c++... duh.. you should be ok

silent bolt
compact pier
#

!learn

tawny elkBOT
#

:teacher: Unity Learn β†—

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

compact pier
#

Yea this one

rigid island
#

yes start with the pathway as was suggested above

vestal arch
#

@compact pier #πŸ’»β”ƒunity-talk message

the logic aspect is transferrable to any similar-level language (which c++ and c# are pretty close)
the language aspect is mostly transferrable between languages of the same family, which c++ and c# are

compact pier
rigid island
#

do Essentials -> Junior Programming, and then go from there

compact pier
#

Daym y'all are so helpful

#

Thnx y'all

vestal arch
#

that's our job description πŸ™‚

rigid island
#

welcome to Unity πŸ˜›

compact pier
#

YESSIRRR

#

And one more thing

#

Do I have to learn blender?

vestal arch
#

if you want to use blender, yes

compact pier
#

For like making 3d models and shi?

rigid island
#

you can use premade assets that are free

compact pier
silent bolt
rigid island
#

but if you want to learn 3d modeling thats up to you

leaden ice
vestal arch
#

if you want to make 3d models, you have to learn how to make 3d models
but blender isn't the only tool for that, it's just the most popular one

compact pier
vestal arch
rigid island
silent bolt
compact pier
#

Like 3d models

somber nacelle
#

the asset store

silent bolt
compact pier
#

THE NAME ITSELF IS ASSET STORE?????

#

LMFAOO

#

Daymmm never knew that

#

Y'all so smart af

vestal arch
#

i mean... the app store is called the app store

compact pier
#

Daym its paid?

vestal arch
#

some of them are

compact pier
#

50 DOLLARS?

vestal arch
#

the author sets the price

#

some of them are free

compact pier
#

Ngl they look good

rigid island
#

you can filter the price to free..

compact pier
#

Yea yea

vestal arch
rigid island
#

also there are more free ones on Sketchfab.com but are not necessarily Unity/Game ready and do require some work in blender sometimes

#

but again you should worry about assets last..esp while learning..

#

use primitves and learn

vestal arch
#

(unless your focus is about making assets, that's fine too, but focus on one thing at a time)

silent bolt
#
Fab.com
Fab

Fab is a digital marketplace that offers creators a single destination to discover, share, buy and sell high quality, real-time-ready game assets, environments, VFX, audio, animations, characters, plug-ins, and more.

rigid island
#

Epic trying to cash in on them unity assets

compact pier
#

There's so much

#

Freeee

silent bolt
compact pier
#

Well well well epic

#

They always

rigid island
#

Unreal store was a flop lets admit it..

silent bolt
#

as if they wouldn't make enought money by dropping a new fortnite skin a day haha

lucid brook
#

Hey, so I am having some trouble with my movement direction when wall running.
I am making a VR game and have an empty gameObject that I set the rotation on the Y axis to that of the player's head so that I can use that as the forwards for moving my player. lookIndex.eulerAngles = new Vector3(0f, head.eulerAngles.y, 0f);
But whenever the player is on a wall, I need to copy the head's rotation but only along the wall's normal.
The problem is that I am terrible with rotations, so I don't even know where to start.

rigid island
#

I'm sure there is also some secret sauce function you can use also in the Vector3. struct for doing additional heavy lifting

#

iirc Project or Project on plane? something like that

lucid brook
undone root
#

umm is it normal that i have to close vs code for my code to compile?

lucid brook
#

no

somber nacelle
#

by "close vs code" do you actually mean just tab back into unity? because that is normal

undone root
#

does anyone here know how to fix that it's driving me insane 😭

undone root
#

like my changes show up in the editor but they won't actually compile until i close vs code

rigid island
#

wdym changes show up in editor ?

undone root
#

the inspector in the unity editor

lucid brook
#

is your game running while this is happening?

undone root
#

no

steady bobcat
undone root
#

im on linux if that matters

undone root
steady bobcat
#

Do you save your changes then to go back to unity?

#

Or is it literally only when vs code is closed it will allow recompiling?

undone root
steady bobcat
#

perhaps its not actually working then?

#

In unity you can re import any script to make it recompile, if the file changes still dont show then its clearly not working.

undone root
#

i've tried turning it off and manually saving as well

undone root
steady bobcat
#

Then i bet its some linux bullshit

undone root
#

yeah i thought so too

#

ive tried looking it up but i don't think anyone else has this problem πŸ’€

cold parrot
cold parrot
undone root
#

wait hol up ill send a video

#

WTF WHY IS IT WORKING NOW

#

OHHHHHH I KNOW THE CAUSE

undone root
steady bobcat
#

Wow thats kinda dumb but perhaps the editor isnt notified correctly of it regaining focus so it never recompiles?

undone root
#

i was legit stuck on this for an embarrasingly long time

steady bobcat
#

open a bug report so it can get fixed

silent bolt
#

it's sad that unity's learning platform has a lot tutorials where the videos are broken.. makes it all harder

silent bolt
somber nacelle
#

i can confirm that same issue is happening in both firefox and chrome, likely an issue on unity's end

silent bolt
#

it was really relaxing to watch how the stuff is done πŸ˜„ hm.. maybe it'll work tomorrow.. i should take a break

somber nacelle
#

yeah, the issue is likely temporary. but i'd recommend submitting a bug report or support ticket or whatever

silent bolt
arctic rune
#

I have no idea which channel this would be for but I'm currently trying to edit a weapon in the fps microgame template. Specifically the shotgun's projectile. I want to make the distance it can travel very short however I cannot figure out how to change this in the inspector. I've tried to find something that documents what everything in the project does but I haven't found anything.

leaden ice
#

if not, it's not necessarily true they've exposed something in the inspector for it

#

Could be a good project for you to add it as a learning experience.

arctic rune
#

tho its really picky what number I choose

#

going off by 0.01 seems to make it go from traveling the same long distance to not traveling even an inch

#

I'll have to treak it a lot but I think that'll work, thanks!

night harness
#

Just playing with ideas not looking for an alt. solution for singletons but learning up abit on interfaces more and just curious, logically this "should" work right? But it's not because I guess it's almost a weird order of execution thing with definitions since in theory any monobehaviour implementing ISingleton<M> would in itself be implementing ISingleton which fufills the generic restriction

public interface ISingleton { }

public interface ISingleton<M> where M : MonoBehaviour, ISingleton
{

}

This does not work

public class ContentManager : MonoBehaviour, ISingleton<ContentManager>
{

}

This does

public class ContentManager : MonoBehaviour, ISingleton, ISingleton<ContentManager>
{

}
#

oh i did not know you could generic restrict to itself that is cursed

public interface ISingleton<M> where M : MonoBehaviour, ISingleton<M>
{

}
#

i also just realised I wasn't even inherting from ISingleton what am I doing this morning 😭

leaden ice
night harness
#

Removed some of the stuff in them since I was just specifically curious about the interface part of the problem for learning but c# 11 has static abstract in interfaces support and i was just curious what usage of that for singletons would look like when we can eventually use it

#

Though even with just the marking it's helpful for a little helper class to avoid re-implementing singleton pattern logic every time where the marker is just used to explicitly say I expect this to act as a singleton

public static class Singleton<B> where B : MonoBehaviour, ISingleton<B>
{
    private static B _instance { get; set; }

    public static B Get()
    {
        if (_instance == null)
        {
            Debug.Log("Finding Singleton...");
            _instance = Object.FindFirstObjectByType<B>();
        }
        return (_instance);
    }
}
leaden ice
#

Solutions like this already exist just using a regular base class though

night harness
#

Forsure but as mentioned previously this is mostly for learning than solving a specific problem I have rn. But the benefit here would be that this could be implemented in a helper/toolkit package that wouldn't require you to use a specific base class to build off of

craggy pivot
#

Does DontDestroyOnLoad affect the parent-child relationship of objects?
I made my GUI mark itself as DontDestroyOnLoad, and it's keeping itself and it's children around when the scene changes, but I'm getting an error saying that a child I'm clearly seeing in the Hierarchy isn't there.

print(cardContainer); // Abilities panel
print(index); // 0 in the screenshot
print(cardContainer.GetChild(index)); // error
leaden ice
#

might be a good idea to log more things

#

like cardContainer.childCount

craggy pivot
#

Sure, one sec

leaden ice
#

it may be that you are referencing the wrong object here. Maybe there's another object in the game world called AbilitiesPanel at the moment.

craggy pivot
#

Maybe... the child count says 0

#

I'll look again.

leaden ice
#

yeah I imagine it's a different object

#

either that or this code is running at a different time than you expect

#

you can also add the object as the second parameter to Debug.Log

#

that will let you click the log and be taken to the object in question

craggy pivot
#

It was another object

#

There was a duplicate of the gui

#

Thank you for helping me find that

dawn nebula
#

I want to get dictionary-like behaviour in a scriptable object, but unity obviously cant serialize an actual dictionary. Any tips?

vestal arch
#

you could use a list of structs (each representing a dict entry), or use the serializeddictionary plugin

#

you could also do 2 separate lists for keys and values, but that's not very good dx

dawn nebula
#
[Serializable]
public struct KeyedAsset<TKey, TValue>
{
    public TKey Key;
    public TValue Asset;
}

public abstract class AssetMap<TKey, TValue> : ScriptableObject
{
    [SerializeField] KeyedAsset<TKey, TValue>[] elements
    private Dictionary<TKey, TValue> cache;

    void OnEnable()
    {
        cache = elements.ToDictionary(e => e.Key, e => e.Asset);
    }

    public bool TryGetAsset(TKey key, out TValue asset)
    {
        return _cache.TryGetValue(key, out asset);
    }
}```

Got something like this.
vestal arch
#

so basically that first option there yeah

dawn nebula
vestal arch
#

not familiar with SOs, so can't help with that, sorry

#

could try the 2nd option i listed, i suppose

dawn nebula
#

Maybe I just also set the cache in OnValidate?

cosmic rain
#

You could also maybe use initialize on load attribute

#

Ah, that's only available in the editor.

night harness
#

iirc using both onenable and onvalidate ends up doing all the right times?

#

oh wait for this is ISerializationCallbacks not the move?

cosmic rain
#

OnEnable should work as well I guess at least in the build.

#

On validate if you want it to regenerate on changes to the SO in the inspector.

night harness
#

from memory both onenable and onvalidate miss one usecase but using them both covers their own bases. but for this serializationcallback should run correctly unless im tripping

cosmic rain
night harness
#

the example is a dict πŸ˜„

cosmic rain
night harness
#

yeah im suggesting to use this instead

cosmic rain
#

Aah. You can do that, yes.

pastel patio
#

Hey guys, I made an async function to transition to and run a state until end, though what I'm not sure about rn is what cancelling this function should mean?

steady bobcat
pastel patio
#

Uh... Thanks, but I mean what makes sense for its cancellation behavior

#

You can't just cancel a transition in Unity... I think, even if it does, would that mean that it falls back to the state before transition?

steady bobcat
#

Well its up to you but it can either revert back or jump to the end?

#

Its your transition logic after all

cosmic rain
pastel patio
#

Well... The function I made does "Play till finish"

cosmic rain
#

Is it an animator state transition? A scene transition? Something else?

pastel patio
cosmic rain
#

Crossfade what? Are we talking about animations?

pastel patio
cosmic rain
#

Okay. Then it's up to you to decide what your methods do on cancelation.

steady bobcat
#

For animators a transition can be cancelled only by another wanting to begin so it will be in a valid state still

#

If it was able to be cancelled and stay mid transition that feels un desirable

#

So if you always intend to perform a new transition then the old cancelled one just stopping without any more changes may be the way to go

cosmic rain
#

An animator transition actually means that the next state is already playing.

#

The previous state weight fades out during the transition

pastel patio
#

I think that I'll add two parts to it...

  1. The abstracted animator will cancel by itself whenever another Play function has been called, this is not externally accessible.
  • This is to address the fact that Play() does, in fact, affect certain fields after the first await.
  1. Externally, if you want to skip waiting for the animation to finish playing, simply use AttachExternalCancellationToken, the current state being played simply cannot be cancelled from the outside without playing another state.
  • AttachExternalCancellationToken is a feature from UniTask, and simply neglects the outcome and moves on
#

Does this seem sane? xD

steady bobcat
#

Usually you provide a cancellation token argument to use in the function which is checked and used to "cancel" the operation

#

I think this unitask extension makes a new task that will compleate early if the token is cancelled BUT the other task ofc is un affected as its not magic

#

@pastel patio I recommend you add a CancellationToken token arg and use this to correctly cancel things

pastel patio
#

Which means that the abstracted Animator might better run separately from other code, rather than reset/skip till end when the current state is cancelled, while the Play function is merely a mean to wait till the AnimatorState finished playing

stable owl
#

Hello, I am currently using the Unity-chan Toon Shader 2.9 and am trying to add displacement/height map function to the shader. It already utilizes the DX11 Tessellation features, but for some reason the height map function wasn't included and I want to add it, but I am having trouble navigating the cginc files to add it.

stable owl
steady bobcat
#

hdpr seems to have more settings πŸ€”
I wonder if this new package has any shader graph support (which would make what you want easy to add)

#

dont expect great things for built in rendering anymore btw

stable owl
#

Height map support is a pretty basic thing, and the dx11 shader already has it, I'm just confused on how to add it to UTS. I've seen someone add it to UTS 2.7 and tried decompiling it (and contacting them) but I can make no sense of the code and how they did it.

distant oak
#

Is there anyone who can help me in unity's playerinput actually I don't understand what the problem is so if you are an experienced person can you help me?

vestal arch
halcyon steppe
#

At what interval does while get executed? Same as update?

somber nacelle
#

while loops are not special in any way, they run until completion just like any other loop. they do not get executed at intervals

halcyon steppe
#

would this even work then?

somber nacelle
#

that entire loop executes within a single frame

halcyon steppe
#

ahhhh well thats my problem then

somber nacelle
#

if that is in Update are you sure you don't want it to just be an if statement?

halcyon steppe
#

this is an individual class i created for a list, it doesn't inherit from monoBehaviour, else i would just use update

#

How do I realize a timer then without an update function? is this even possible?

somber nacelle
#

your options are to use Update, a coroutine, or async method. and unless your async method returns Awaitable it won't be part of the typical Update loop so it won't necessarily have the timing you want

halcyon steppe
#

Ohhh i forgot about coroutines, thank you very much!

last quarry
#

There's also C#'s timer class

halcyon steppe
#

Oh interesting, i will have a look

#

thank you too!

somber nacelle
#

do note that the Elapsed event is typically not invoked on the Main thread so if you do stuff that touches unity objects then you're going to have behavior issues when the exceptions for touching unity stuff off the main thread is completely suppressed by the event

halcyon steppe
#

Mate, some day I wanna know as much as you do about unity code.... thanks again!

naive swallow
halcyon steppe
#

I am not quite sure what you mean, in what class do you suggest I create this update method? The class I want to create the timer in cannot inherit from MonoBehaviour and the class creating a list out of cant update multiple timers at once.

somber nacelle
#

and the class creating a list out of cant update multiple timers at once
why not?

#

couldn't whatever monobehaviour you have simply loop through the list and call Update on each one?

halcyon steppe
#

I got a warning, Give me a sec, I need to reproduce it

halcyon steppe
somber nacelle
#

so whatever is being newed on line 189 inherits from MonoBehaviour so you cannot new it

halcyon steppe
#

how else would i do this then?

somber nacelle
last quarry
#

Why does Note inherit MonoBehaviour?

halcyon steppe
halcyon steppe
somber nacelle
#

that's what digi was suggesting

halcyon steppe
#

Okay I am just stupid then, i'm sorry

somber nacelle
last quarry
#

You can just not inherit MonoBehaviour, and have the parent class call the Update method on each

#

Or turn them into structs and have the parent class execute the logic directly

halcyon steppe
#

With my limited knowledge I can at least write this one lol

#

Thank both of you so much, if you weren't strangers on the internet I would buy both of you a beer

last island
#

For some reason this line stationTrackerRenderers[i].materials[0] = trackerMaterials[i]; doesn't actually change the material I have on my MeshRenderer. The renderer's material stays unchanged. And yes, I have checked that the material in the trackerMaterial array is correct.

dusk apex
last island
#

Ah so you have to change the whole array

#

Gotcha

somber nacelle
#

this is why it helps to read documentation.

Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.

last island
#

I missed that part about replacing the whole array really.

#

That's fine. Thanks for the help.

steady bobcat
#

I think its because the property goes to native code for get and set (so requires a write back to do anything)

last island
#

Yeah that's fair.

#
private void UpdateMaterial(int materialIndex, MeshRenderer renderer, Material newMaterial)
{
    Material[] materialsCopy = renderer.materials;
    materialsCopy[materialIndex] = newMaterial;
    renderer.materials = materialsCopy;
}
#

Should do the trick

dusk apex
last island
#

So not sure if I can optimize that somehow

steady bobcat
#

So if given a smart size to begin it should be better alloc wise

last island
#

So if I did this perhaps, and then passed the list to the method to call GetMaterials on?

List<Material> materials = new List<Material>(2);
for (int i = 0; i < stationTrackerRenderers.Length; i++)
{
    UpdateMaterial(0, stationTrackerRenderers[i], trackerMaterials[i]);
}
vital granite
#

Need help understanding the best way to implement a thing
Currently for a script I have it reads info from a text file from the resources folder and stores the information in a class
What I want to try and do is add the ability to write back any updated information from the class back into the text file
I understand that text files stored in the resources folder are only read only and you can't write info to them, though abit confuse on which thing to use that would write back that information into the text file and keep that info between runs of the game

last island
#

So it would then be

private void UpdateMaterial(int materialIndex, List<Material> allocList, MeshRenderer renderer, Material newMaterial)
{
    renderer.GetMaterials(allocList);
    allocList[materialIndex] = newMaterial;
    renderer.materials = allocList.ToArray();
}
steady bobcat
last island
#

Oh right I can use SetMaterials

#

brainfart

somber nacelle
last island
#

That should do it then, I think

naive swallow
#

Also don't crosspost

silk horizon
#

In Unity Localization, how do you add a

silent bolt
#

is this normal to take this long just for a cube that rotates and changes his scale & position?

somber nacelle
#

not a code question. but building can take time, especially for things like webgl, and depending on your build settings

#

hardware speeds also play a role, especially cpu and disk read/write speed

silent bolt
random oak
#

So I have an event coming in another thread from Invoke in a library I'm using, I need to use the main thread in Unity for UI.
How can I bring it back to main thread ?

steady bobcat
somber nacelle
#

using Awaitable won't require another package so would be the easiest (assuming you are on unity 6 or higher)

random oak
#

I See. So I make the receiving method Awaitable then switch the thread there ?

steady bobcat
#

UniTask has a similar function to await and go to the main thread if you prefer it or are on 2022 and earlier.

random oak
steady bobcat
#

Np. I use the UniTask variant with ad watch callbacks as they are often all over the place thread wise

random oak
somber nacelle
#

invoke the Awaitable method from the method that the event invokes

random oak
#

Ohh that makes sense , thanks!

wide totem
#

Generally, for powder/sand games, would each pixel be a (static) game object in unity, or would you write them manually?

When i say game object, i just mean for sprite purposes, not a rigid body with unity physics. Would be simulating sand physics and updating their position β€˜manually’. Just wondering if game objects would take up a considerable amount of memory inherently, and if it would be better to just write the pixels to the screen

random oak
#

@somber nacelle & @steady bobcat worked great! thanks again

wheat shoal
#

Hey for some reason the trigger boxes are not working.

 {
     inFront = true;
 }

 void OnTriggerExit2D(Collider2D collision)
 {
     inFront = false;
 }```
Its just giving me false even when the player is in the collider boxes.
somber nacelle
wheat shoal
somber nacelle
#

have you gone through the steps in the link i sent yet?

wheat shoal
#

oh wait i see more

somber nacelle
#

i mean sure, that's where it leads if you intentionally click the link to the docs, there's more troubleshooting steps after the very first step though

lucid brook
wheat shoal
#

Huh just discovered that Rigid bodies have diffrent body types

#

well at least my player dosent slide no more

#

Fixed my issue btw it was these things set to everything and not nothing

steady bobcat
#

The point I hope to convey is rotating the bob using the wall normal so its relative to that

steady bobcat
#

Hmm i miss understood, you mentioned head rotation

#

there is also a function to raycast and get the hit dist which can be used to get the hit point on the plane.

lucid brook
steady bobcat
#

Do you know what a surface normal is?

lucid brook
#

yes, I already use the normal of the wall for some other stuff

steady bobcat
#

Cool. We can use the Plane object to produce an imaginary flat surface with the same normal and we can then raycast or get the closest point on this plane.
E.g. you do Vector3 newPos = transform.position + (transform.forward * 2f); then ClosestPointOnPlane() to get the move pos but on the plane instead (so its then on the wall instead of in the air)
When constructing Plane you need to give the normal and the dist from world origin which would be the face center pos magnitude.

#

I use Plane myself to let an object be draggable by the mouse/touch but i use Raycast() to keep the movement on a 2d plane I desire.

#
Plane dragPlane = new(transform.up, 0f);

//In OnDrag...
var dragPosRay = eventData.pressEventCamera.ScreenPointToRay(eventData.position);
if (dragPlane.Raycast(dragPosRay, out float hitDistance))
{
    dragPos = dragPosRay.origin + (dragPosRay.direction * hitDistance);
}
brave geyser
# wide totem Generally, for powder/sand games, would each pixel be a (static) game object in ...

I don't have a solid direction to send you in without knowing what exactly your design is, but I can confidently tell you that using a GameObject for each pixel of sand is going to kill you on a ton of different metrics.

If you mean a game like Noita, you could do some digging and see how those games implemented those sorts of systems. They aren't going to be Unity games necessarily, but will give you some concepts and approaches to look into with Unity.

lucid brook
steady bobcat
steady bobcat
lucid brook
#

my code might be very bizarre, lol. but yeah let me spend a bit of time typing up a better message

wide totem
#

Thats what id imagine for the gameobjects (to what both of you said), im thinking that unity just might not be the right type of engine for this project? I’ve heard it has problems with dealing with writing individual pixels on a screen becayse it is a 3d engine

steady bobcat
#

You can easily use a compute shader to update some texture you show on the whole screen.

steady bobcat
#

Though i see no good reason to have an entity per sand particle as that seems needless

wide totem
# steady bobcat Though i see no good reason to have an entity per sand particle as that seems ne...

Im not sure how else you would simulate specific motions for each particle without them being entities of some kind.

The way i imagine it is a 2d array (screen size) of structs for each pixel position, with the struct representing the information stored, such as density, liquidity, movement direction, etc. looping through the array bottom right to top left each frame, mapping the array as pixels to the screen. I could definitely be wrong about that though

steady bobcat
#

yea i would probably go this route too. Entities and ECS could potentially be a good fit still as its optimised for such workflows

lucid brook
# steady bobcat How you describe your movement already sounds strange tbh. Can you share some co...

Alright lets try to explain my weird code, my game is a VR one so I can't rotate the player object around when you look left or right (at least not without unparenting the controllers). So instead of doing that I have an empty gameObject that I rotate only on the heads Y axis to use as the movement direction.

directionIndex.eulerAngles = new Vector3(0f, head.eulerAngles.y, 0f);

Vector3 targetVelocity = new Vector3(moveInputValue.x, 0, moveInputValue.y) * (moveSpeed * moveSpeedMultiplier);
targetVelocity = directionIndex.TransformDirection(targetVelocity);

So whenever I start a wallrun I would ideally need to rotate the directionIndex object along the wall's normal relative to the heads rotation. If that makes sense... and I hope it's not too weird...

steady bobcat
#

So you use another Transform that is rotated to match the camera world Y rot to then get a "forward" direction?

lucid brook
#

yes

steady bobcat
#

you can still use this "forward" but project on a plane for the wall to keep the movement affixed on the wall

lucid brook
#

yes, but then looking to the left would make the player go down the wall and looking right would make them go up it. instead of that being done with looking up and down.

steady bobcat
#

why would that be? have you tried it?

#

the point is to move them on the wall plane instead of world XZ

lucid brook
#

I've tried something similar I think. But the only rotation I am giving the directionIndex object is the heads Y rotation. So the only 'input' I give it is looking left and right, up and down isn't even accounted for.

steady bobcat
#

if its world y rot cant they still walk off the wall?

lucid brook
#

How do you mean? Like the wall being to your left and you walk to the right?

tough carbon
#

I would like to make floating text above the character (2D). But it rotates with character, so I were told to make independent object with text and make it follow character. How could I create prefab with it? I don't want bind text any time I create object

vestal arch
#

you could have it be a child but counterrotate to stay in the same orientation

tough carbon
vestal arch
#

because that's what parenting an object does, it inherits the parent's transform

#

you could have the script unparent the canvas and then copy the player's movement, i guess?

#

that'd be the other option

steady bobcat
dawn nebula
#

I have a class here whose properties are meant to be set in the inspector, and I don't want them to ever be changed.

[System.Serializable]
public class CardTypeData
{
    [field: SerializeField] public Sprite TypeIcon { get; private set; }
    [field: SerializeField] public PlateData PlateData { get; private set; }
}

The issue is that if I ever wanted to make an instance of this class in code, I would never be able to set these values. I know Unity does not play well with constructors and serialization. Any tips?

rigid island
dawn nebula
rigid island
#

you can probably have another constructor with params if you want to create it with specific values? or make an Init method?

torpid osprey
#

Is there a difference when calling isGrounded after or before moving the character controller in the update method?

tough carbon
steady bobcat
#

I would have expected locking rotation to stop that rotating though πŸ€”

steady bobcat
#

its still a child of the object 😐

#

You need a script to keep setting its world rotation to Quaternion.Identity each frame

tough carbon
#

I am sorry, I am being stupid

steady bobcat
#

Yea those constraint components can be used when its NOT a child so it can copy position and/or rotation

#

otherwise transform children will work as normal

tough carbon
shell scarab
#

why does this if statement not fail?

private void EditorSceneManagerOnSceneClosing(Scene scene, bool removingScene)
{
  Debug.LogError("1");

  if (GameObject.GetScene(GetInstanceID()) != scene) return;

  Debug.LogError("2");
}

I only have a single scene open, and this script is on a game object in that scene. So shouldn't this reach the Debug.LogError("2") line?

somber tapir
shell scarab
somber tapir
#

probably GetInstanceID isn't the value you expect it to be

shell scarab
#

you think that Object.GetInstanceId doesn't return the instance ID that GameObject.GetScene needs?

#

Debug.Log(EditorUtility.InstanceIDToObject(gameObject.GetInstanceID()));/Debug.Log(EditorUtility.InstanceIDToObject(GetInstanceID())); works fine.

brave geyser
#

I've never used that event before. I'm not sure when GameObjects start getting destroyed in that process, but that could be in work before this event fires and is caught. Can you get the instance ID before this line, like in a separate Debug.Log call?

leaden ice
#

Also couldn't you just do gameObject.scene?

shell scarab
#

Yes, the problem was I was getting it of the component. I feel like it’s a bit misleading to say the component doesn’t belong to the scene.

I didn’t use that because I was trying to get the scene of the component.

leaden ice
#

Getting the scene of the component, how would that be different from the GameObject it's attached to?

shell scarab
weak thicket
#

im attempting to sample an audio source with a small script, but it isnt.. working.. I think I messed up significantly in the script somewhere.
But, it is attatched to the audiosource gameobject, and the audiosource is audible.


public class OVC_AudioSampler : MonoBehaviour
{
    public float currentAmplitude = 0f;
    public float updateRate = 0.5f;
    private float currentTime = 0.0f;
    public int channels = 1;

    void Start()
    {

    }

    void Update()
    {
        if (currentTime >= updateRate)
        {
            GetAmplitude();
            Debug.Log("ASUpdated!");
            currentTime = 0.0f;
        }
        else
        {
            currentTime += Time.deltaTime;
        }
    }

    void OnAudioFilterRead(float[] data,int channels)
    {

        for (int i = 0; i < data.Length; i += channels)
        {
            float sample = data[i];
        }

        Debug.Log("Datapoint 0 " + data[0].ToString("F10") + " Sampled");
    }
    public float GetAmplitude()
    {
        return currentAmplitude;

    }
}
#

The second debug log that outputs the data[0] goes off, but that data stays at 0 even when audiosource is playing

#

its meant to analyze live audio

leaden ice
#

That's what links it to the native instance
@shell scarab

weak thicket
leaden ice
hybrid thistle
#

Hi. I've been debugging and researching for a few days now and I can't figure out why one of my GameObject's transform is showing a child count of 0 when I debug (Rider), but simultaneously shows having a child object in the scene and hierarchy.

Any help would be appreciated. I will try and provide as much context as possible:

-The parent object ("contentsContainer") is a part of the scene, but not a prefab
-The child object becomes a child via "transform.SetParent(parentObject.transform)" during runtime.
-> At any given time after this, the user may click on an object (called "Inspectable") with a script containing "IPointerClickHandler"
this object has a reference to the parent object (assigned via the Inspector before running)

I have debugged and confirmed the following:
-The Instance ID of the parent object referenced is the same as the object I am viewing the in hierarchy
-The parent object has a test script attached to it that debugs using the update function confirming it has the child object and a child count of 1
-The function that is called within OnPointerClick() shows the refrenced parent object having a child count of 0 while the scene shows otherwise.
-The inspector confirms the correct object is referenced from the "Inspectable" script.

wicked scroll
hybrid thistle
wicked scroll
#

you have the wrong one

hybrid thistle
#

this one?

wicked scroll
#

the inspector is for the one in Player, the debugger is the one in Opponent

hybrid thistle
hybrid thistle
weak thicket
vivid heart
novel bough
steady bobcat
steady bobcat
#

then may be unity enforcing this for compatibility on win too

#

just do _con or something similar

wintry crescent
#

on an interface, I have
public string ID {get;}
and
public virtual string OrderKey => ID;
Then in a class implementing this interface, I cannot override the OrderKey, why is that?

unkempt meadow
#

I can only see the instance where it goes out of the reach of the IK chain but I don't think that's happening here

steady bobcat
#

is OrderKey in the interface? me confuse

night harness
steady bobcat
#

then doesnt need to override to implement the interface

wintry crescent
#

yes, it's in the interface. Turns out that since it's virtual I had to provide the implementation both in the interface, AND in the deriving class for it to work, so that then I can override it in the class that is further down the chain

steady bobcat
# wintry crescent yes, it's in the interface. Turns out that since it's virtual I had to provide t...

interfaces technically cannot do this, what you did was give a "default implementation": https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods

#

use an abstract class instead

wintry crescent
steady bobcat
#

should be a combination of both then

dark salmon
#

Is there anything wrong with shoving your entire save data into one single json instead of breaking down per category?
Like, let's say you are running a simulation that can have upwards of hundreds of characters. Instead of having individual jsons for each character in your persistent data path can you just have 1 savedata json with a List<Character>?

chilly surge
#

It will probably come down to how often you update all characters vs how often you update just some characters.

steady bobcat
#

JSON isn't fast at a large scale so many files may be better when things are large

cold parrot
steady bobcat
#

Sqlite is a good choice but I don't know if there are wrappers in c# and ofc you will need binaries for other platforms

cold parrot
#

there is a general problem that embedded databases are not something thats needed much outside gamedev (most would at that point want to use remote or separate-process DB), so beyond sqlLite there hasn't been much development

#

also SQLite is pretty good. But its still a RDBMS so you will need to do some ORM, which is annoying

primal wind
#

EFCore's SQLite adapter works fine but i never checked if it support netstandard and anything other than desktop platforms

#

Tho it seems to be limited

cold parrot
naive swallow
# novel bough I can not change name "con" evenif there are no same name in folder

The short answer is "backwards compatibility". The long answer is... well, it's the rest of this video.

MORE BASICS: https://www.youtube.com/playlist?list=PL96C35uN7xGLLeET0dOWaKHkAlPsrkcha

Written with Sean Elliott https://twitter.com/SeanMElliott/
Graphics by William Marler https://wmad.co.uk
Audio mix by Graham Haerther https://haerther.net...

β–Ά Play video
#

(Unity probably enforces this even on other platforms for compatibility)

karmic stone
#

Quick question about copying collider components at runtime. Is using reflection the best possible way to do this, or is there a better way for specifically collider objects? Im making a system that involves using different type of colliders based on the object thats attached, and i need to make a copy of the obj colliders when the object is placed.

vestal arch
#

sounds like prefabs could simplify that workflow

karmic stone
#

its a system of growing crops, and i use the collider of the grown crop for its ability to be placed. once its placed, it turns into a seedling version, but i still need the collider from the last grown crop to prevent other crops being placed on it

iron phoenix
#

Previously I could use this code in a project to show only sprites in a specific folder, but I just can't make dir work whatsoever in this project.
Any ideas? Unity 6000.0.45f1

 
int controlID = EditorGUIUtility.GetControlID(FocusType.Passive);
EditorGUIUtility.ShowObjectPicker<Sprite>(ItemIcon, false, "t:sprite dir=\"Items\"", controlID);

karmic stone
iron phoenix
#

I tried full path with both \ and /, didn't work sadly (Assets\Art\UI\Icons\Items)
I also tried with : instead of = t:sprite dir:"Assets\Art\UI\Icons\Items"
Also with/without " "

brave geyser
#

You should output the directory name to see what the compiler thinks you're telling it when you're in this situation.

Looks like you need to use \ for each , though. First slash tells compiler the next character is a special character and not text. So right now it's trying to interpret A, U, I, and I as something special.

iron phoenix
#

but I test it in the selector manually as well, and it doesn't work there?

brave geyser
#

Your original code was reading "Items" as the search term, I see now. I guess I'm not certain how that interface would work, but I assume in code .ShowObjectPicker is wanting a string, and so the string escape characters are expected.

#

"t:sprite dir=\"Assets\\Art\\UI\\Icons\\Items\""

#

Edited above to add quotes around whole search term.

iron phoenix
#

didn't work sadly, thanks tho πŸ™‚ I get your point and I have tested it earlier :\

vestal arch
#

do you perhaps also need to escape the path separators?

#

if so that'd be 4 \ per path separator

iron phoenix
#

I tried to put a sprite directly in the Assets folder as well, and I can't even make that one show up with dir: / dir=
4x \ didn't seem to do it sadly

#

auuuu, I just remembered there was a "advanced" option for the search engine.. now it works πŸ₯²
EditorGUIUtility.ShowObjectPicker<Sprite>(ItemIcon, false, "t:sprite dir:Items", controlID);
Thanks btw πŸ™‚

leaden ice
karmic stone
# leaden ice Instantiate copies the whole object

I dont really need to Instantiate a full obj, just a single collider component. i want to connect it to an already existing gameobj, as both the gameobj i want it on, and the one im copying from are already instantiated

leaden ice
#

there's no easy way to instantiate a single component

karmic stone
#

i was asking if reflection was the best way to instantiate a single component, copying fields /properties. but otherwise, i could just switch the transform.parent of the collider obj, if that would be better then a full instantiation copy.

leaden ice
#

Reflection is not a good way, no.

karmic stone
#

is there a better way to do the instantiating single components, or is it not worth it in any way.

leaden ice
#

there is not a better way

#

Unity could provide one by giving us more granular access to their serializer, but they haven't.

steady bobcat
#

There are many things unity could give us like some kind of runtime scene saving but they never have

#

Logic is there to parse this stuff after all πŸ€”

karmic stone
#

if i could extend colliders, then i could also do it that way.

weak thicket
leaden ice
#

it's interleaved like it says

#

if there are 2 channels, then it just alternates between them

#

element 0 of the array is the first element for channel 0.
element 1 is the first element for channel 1
element 2 is the second element for channel 0
element 3 is the second element for channel 1
and so on

weak thicket
#

i see... and since there are 1024 elements, and 2 channels in my case, there are 2048 elements in the array...
therefore, if I try to sample position 500, I would get the 250th element of channel 2?

leaden ice
#

i think position 500 would be the 251st element for channel 0

#

there would be no channel 2

#

just 0 and 1

weak thicket
#

ah,
the channels variable is how many channels there are? Since mine outputs 2 for this variable, there are 2 channels; 0 and 1?

#

I do have it running on the audiosource, but its not getting anything, all of the data elements I checked are at 0, even with audible audio playing

weak thicket
#

I did check a few, not all of them though...

leaden ice
#

just check them all in a loop

#
bool allZero = true;
foreach (var sample in data) {
  if (sample != 0.0f) {
    allZero = false;
    break;
  }
}

Debug.Log($"All samples are zero? {allZero}");```
weak thicket
#

ok used that, and yea its all zero

leaden ice
#

THat's odd...

weak thicket
#

huh...

weak thicket
#

I am coding this to function with Udon, which did allow "OnAudioFilterRead(float[] data,int channels)" to run...
Though I just learned that this functionality was disabled at some point, so I need to use a different method

steep herald
#

sanity check please,

someMeshRenderer.bounds.size returns (2.83, 2.83, irrelevant)

local bounds however are (2, 2, irrelevant)

  • actual mesh size is 2 units wide/tall.
  • Every single transform in the hierarchy has a scale of 1.
  • iterating through verts of the shared mesh confirms 1 being the extents, so 2 being the size.

Why the hell does the world bounds of the meshrenderer even suggest 2.83?

cosmic rain
steep herald
#

@cosmic rain no, simple mesh renderer. Just now noticed that setting rotation to identity seems to return proper world bounds, but I am confused. The mesh is basically a ring, even if rotated how could it make the AABB larger?

cosmic rain
steep herald
#

Yeah but I can't figure out how a ring/sphere could stretch the bounds

cosmic rain
#

It's a box. Not a ring or a sphere

steep herald
#

Yeah, but the box is made to contain a sphere, so it should always be the same size

cosmic rain
#

Perhaps it's not just a sphere then. Maybe there's a rogue vertex somewhere making it not symmetrical

steep herald
#

I assumed that as well, but I iterated through verts and really seems like 1 is the max value

cosmic rain
#

Then I'm not sure.

steep herald
#

Thanks anyway

cosmic rain
#

Btw, a ring shape is not symmetrical on all axis, so it's bounding box might be changing while it's rotating. But regarding a sphere I'm not sure. Could be a bug.

steep herald
#

value coincides with sqrt(2^2 + 2^2), doubt that's an accident

#

ok so I think it computes the local AABB/OBB and then transforms that

cosmic rain
#

What value are we talking about?

steep herald
#

so thats why its projected like a cube

cosmic rain
#

Is it the magnitude of the box size?

steep herald
#

Yeah, 2.83 would be the size of the AABB of a cube* of an actual size of 2 if it had been rotated by 45 degrees

#

so likely tied to what's happening. My guess is it computes the bounds in local space and then applies a transformation to that, so it ends up applying a transformation to a cube

#

instead of my ring/sphere, and the bounds end up being larger than what is immediately needed to contain the sphere

cosmic rain
#

Perhaps. Maybe look at the meshrenderer.bounds docs page. It has an example of how to visualize them.

steep herald
#

Aye. I'm going to go with the theory that this is what's happening. It'd make sense, it'd allow them to precompute the bounds during the mesh import process and then just apply transformations instead of recomputing entirely

#

thanks for the interest/help!

quartz sun
#

Hi I'm working on a 2D platformer project for my portfolio. I started learning about the Spline Component from some tutorials and the basics online. But I'm a little stumped at a problem with my new mechanic. Whenever I make contact with the rail I can only start at the beginning or the end of the rail?

leaden ice
tawny elkBOT
quartz sun
#
public class PlayerRailGrind : MonoBehaviour
{
    private PlayerMovement playerMovement;
    public SplineContainer RailPath;
    public float speed;

    public float RaildistancePercent = 0;
    private float railLength;
    private bool IsOnRail;
    private bool IsRailGrinding;

    public float linedistance;
    public LayerMask RailLayer;
    public Transform FeetToRail;
    public float Offset;
    void Start()
    {
        playerMovement = this.gameObject.GetComponent<PlayerMovement>();
        railLength = RailPath.CalculateLength();
    }

    public bool OnRail()
    {
        IsOnRail = Physics2D.Raycast(new Vector3(transform.position.x, transform.position.y, transform.position.z), Vector2.down, linedistance, RailLayer);

        if (IsOnRail)
        {
            RaycastHit hit;

        
        }

        return IsOnRail;
    }

    private void FixedUpdate()
    {
        OnRail();
        if (Input.GetKeyDown(KeyCode.Space) && OnRail())
        {
            playerMovement.physics.AddForce(Vector2.up * playerMovement.JumpSpeed, ForceMode2D.Impulse);
        }
        if ((playerMovement.Direction().x > 0 && OnRail()) || (playerMovement.Direction().x < 0 && OnRail()))
        {
            speed = 5.75f;
        }
        if ((playerMovement.Direction().x == 0 && OnRail()))
        {
            speed = 5;
        }
    }
    public Vector2 direction;
    // Update is called once per frame
    void Update()
    {

        // Cast a ray in the direction specified in the inspector.
        RaycastHit2D hit = Physics2D.Raycast(transform.position, direction);

        // If something was hit, draw a line from the start position to the point we intersected.
        if (hit)
            Debug.DrawLine(transform.position, hit.point, Color.yellow);
        Debug.DrawRay(transform.position, Vector2.down * linedistance, Color.red);

        //If is falling and contacts rail
        if ( playerMovement.physics.linearVelocityY < 0.01f && IsOnRail)
        {

            Vector3 currentPosition = RailPath.EvaluatePosition(RaildistancePercent);
            FeetToRail.position = currentPosition;

            playerMovement.physics.gravityScale = 0;

            if(this.transform.localScale.x == 1)
            RaildistancePercent += speed * Time.deltaTime / railLength;

            if (this.transform.localScale.x == -1)
                RaildistancePercent -= speed * Time.deltaTime / railLength;

            Vector3 newPosition = new Vector3(FeetToRail.position.x, FeetToRail.position.y + Offset, FeetToRail.position.z);
            this.transform.position = newPosition;
           


            if (RaildistancePercent > 1f) { playerMovement.physics.AddForce((Vector2.right + Vector2.up) * playerMovement.JumpSpeed, ForceMode2D.Impulse); RaildistancePercent = 1f; }
            if (RaildistancePercent < 0f) { playerMovement.physics.AddForce((Vector2.left + Vector2.up) * playerMovement.JumpSpeed, ForceMode2D.Impulse); RaildistancePercent = 0f; }
        }
        else
        {
            playerMovement.physics.gravityScale = 1;
            FeetToRail.position = new Vector3(0f, -0.888999999f, 0f);
        }
    }
}
#

I'm currently trying to see how I can use Raycast hit to maybe help calculate the RaildistancePercent

dawn nebula
#

If I wanted my text to glow (like through Bloom) what do I need to do?

#

Text colors for TextMeshPro do not seem to be HDR

leaden ice
cosmic rain
#

If you make it render before it, it might work.

dawn nebula
cosmic rain
#

You can check with the frame debugger

dawn nebula
cosmic rain
#

Okay. And they are not affected by bloom in your case?

dawn nebula
#

so I can't control the amount other than with the global intensity value

cosmic rain
dawn nebula
cosmic rain
wicked scroll
#

there's an attribute to tell it to use HDR color I think?

dawn nebula
#

Color in the material is no longer HDR.

vestal arch
#

@steep herald i see you've already gotten a conclusion, but perhaps try Gizmo.DrawWireCube to visualize the bounds if you'd like to strengthen that conclusion?

young yacht
#
IEnumerator WaitForCardsShow()
    {
        // if (enemiesSpawnedList.Count != 0)
        // {
        //     foreach (var enemy in enemiesSpawnedList)
        //     {
        //         Destroy(enemy);
        //     }
        // }

        yield return new WaitForSecondsRealtime(0.5f);

        playerController.DisablePlayerMovement();
        playerController.playerInput.Player.EscMenu.Disable();
        playerController.playerInput.Player.Aiming.Disable();

        if (waveIndex % 5 != 0)
        {
            for (int i = 0; i < itemCardsButton.Count; i++)
            {
                int index = i; // capture i in a local variable
                itemCardsButton[i].onClick.RemoveAllListeners();
                itemCardsButton[i].onClick.AddListener(() => ClickItemCard(index));
            }

            Time.timeScale = 0f;
            ShowCards();
        } else 
        {
            for (int i = 0; i < itemCardsButton.Count; i++)
            {
                int index = i;
                itemCardsButton[i].onClick.RemoveAllListeners();
                itemCardsButton[i].onClick.AddListener(() => ClickSpecialItemCard(index));
            }
            
            Time.timeScale = 0f;
            ShowSpecialCards();
        }
    }

does anyone know why Time.timeScale isnt working?

night harness
#

whats not working

young yacht
#

i want to stop the game when the cards show on the screen

#

this is my switch case where i start the coroutine:

void Update()
    {
        switch (waveState)
        {
            case waveStates.StartWave:
                SpawnEnemies();
                break;
            case waveStates.Cards:
                if (!isShowingItemCards)
                {
                    StopAllCoroutines();
                    StartCoroutine(WaitForCardsShow());
                    isShowingItemCards = true;
                }
                break;
            case waveStates.Countdown:
                Countdown();
                break;
            case waveStates.Break:
                Break();
                break;
            case waveStates.NextWave:
                NextWave();
                break;
            case waveStates.Miniboss:
                WarnMiniBossSpawn();
                break;
        }
    }
#

the game doesnt seem to be stopping

night harness
#

what is not stopping

young yacht
#

its working when i open my esc menu

#

but not with this different script

night harness
#

what is not stopping

young yacht
#

time

night harness
#

What do you consider to be time

hexed pecan
#

Yeah what exactly is happening in the game?

#

Because it might or might not be tied to time scale

young yacht
young yacht
#

just how you see in vampire survivors when the level up UI shows up

night harness
#

animations is a correct response

#

what is character and enemy movement

young yacht
#

why are you all phylosophical

night harness
#

Because "stopping time" is a conceptual expectation of a logical piece of software

#

setting Time.timeScale specifically affects certain things

#

to figure out why its not working you need to figure out if it should be working

young yacht
#

my point is its doing exactly what i expect when i Time.timeScale = 0 with my menu, but not with my waveManager

#

which is "stopping" the game

night harness
#

Ok but I am not you and I need to be aware of those expectations, hence the questions

hexed pecan
#

Have you first checked that the timescale actually stays at 0 during the period

young yacht
hexed pecan
#

Where did you debug it?

#

You can also open the Time settings in unity, altho it might not repaint the window unless you hover it

night harness
#

(and also still worth specifying what character and enemy movement mean)

young yacht
#

its only going to 0 for a frame apparently

#

then goes back to 1

night harness
#

then its probably your switch statement

#

what is meant to set it to 1f

young yacht
#

is it okay to time.Timescale = 0f in the update function?

#

going every frame

night harness
#

i mean its fine but it doesn't do anything

young yacht
night harness
hexed pecan
young yacht
#

so i only change the timeScale in one place

robust berry
#

In the editor it says
"String based property lookup is inefficient"

animator.SetFloat("Speed", moveDir.x);

#

is there a better way?

somber nacelle
#

cache the result of Animator.StringToHash and use that in place of using the string

#

and note that you should only be calling StringToHash once per string, not every time you go to call that SetFloat method otherwise it's exactly as inefficient

dense crow
#

how can i make my enum expandable while keeping it optimized ? like loading the enum from a text file, my only idea is to use int as id instead but it is hard to debug

{
    Calm, Stubborn, Annoying, Diligent, 
}```
night harness
#

define optimized

#

I personally use ScriptableObjects in place of a lot of enums

dense crow
night harness
#

I mean in that case the int could be an index pointing to various things

vagrant blade
#

What's wrong with adding more to your enum?

dense crow
# vagrant blade What's wrong with adding more to your enum?

my enums have effect value , like apply diligient on a man change his iq 2, etc.. so if i use enum, when i modify the enum script i also have to modify the dictionary effect script, i also have other properties like this. It is so easy to make mistake

cosmic rain
#

Well, how is making it expandable gonna help with that?

#

Wouldn't it be the same as adding new values manually?

dense crow
cosmic rain
signal herald
#

I think I would just write a for loop to iterate through the dictionary to check if all items match the length of the Enum. Then output an error if false.

mint mural
#

how do I accomplish something similar to the SpriteRenderer component which uses one material for multiple textures?

#

I want to do something similar for one material and multiple values for a single variable

#

I read about MaterialPropertyBlock but the doc states that it costs performance in URP

#

and creating multiple material instances doesn't seem much better

cosmic rain
mint mural
#

I found an option called 'hybrid per instance' in the 'scope' property for the variable that I want to accomplish this for

#

but it doesn't seem to work

#

(this is in the shader graph)

#

oh wait a sec I think it works only for scripts I'll try that out first

dense crow
#

the MaterialProperyBlock also work fine

steady bobcat
#

It also uses vertex colours for the tint

wraith spear
#

Hi all, I'm having some problem with the Pixel Perfect Camera in my scene. As you can see in the video below, UI elements "jitter" during movement (overview of Scene hierarchy incoming)

steady bobcat
wraith spear
vestal arch
#

rubber duck moment

wraith spear
# steady bobcat ui document or canvas (screen space overlay?)?

I have a bootstrap scene with the main camera and a standard canvas. That UI is Screen Space Camera with an assigned Camera. In each scene I use a separate canvas for scene-specific things, als Screen Space Camera. Here the Camera is never assigned, however, and those UI elements don't experience the jitter.
By setting the bootstrapper canvas to Screen Space Camera without a camera assigned, it fixed the issue. Going to look into why it fixed the issue & whether I have the correct set up now. If anyone has suggestions, they're more than welcome!

steady bobcat
#

not sure myself but any reason for it not to be screen space overlay?

wraith spear
#

Not sure, I set this up months ago and only recently noticed the jitter. Testing it now to see how it looks

#

Yeah Overlay works as well, I'll be using that. Wasn't using the Normal and Tangent Shader Channels anyway

weak thicket
#

now that I have an output with the audiosource in a 1024 array with the spectrum moving 0-24,000Hz.
How should I split it into four bins?

olive ridge
#
            {
                dot.transform.Translate(0.1f, 0, 0, Space.Self);

                distance1 = Vector2.Distance(transform.position, city1.position);
                distance2 = Vector2.Distance(transform.position, city2.position);
                distance3 = Vector2.Distance(transform.position, city3.position);
            }

does this make the while loop infinite, cause it caused the playmode to not load

dusk apex
leaden ice
quartz folio
#

Even if it did end there's no yield in the loop so it begs the question why it's a while as it'll execute in one frame

leaden ice
#

anyway there's no reason for this to be a loop... yeah exactly this^

cursive coral
#

Is there a easy and effective way to change the direction in which unity physics gravity acts. For example dynamically changing the gravity to be in x axis during gameplay.

leaden ice
#

Physics.gravity = whatever;

olive ridge
cursive coral
leaden ice
#

yep Β―_(ツ)_/Β―

cursive coral
#

One line of code

leaden ice
#

why wouldn't it be?

cursive coral
#

Is physics.gravity accessible

cursive coral
#

I don't have my pc rn so can't check

leaden ice
leaden ice
olive ridge
#

it moves the dot away from another object and recalculated their distance

cursive coral
cursive coral
leaden ice
#

so moving the dot won't change that distance at all

olive ridge
#

ohhhh

#

i see it now

leaden ice
#

anyway read the rest of what we wrote - the loop makes no sense even if you didn't have that error

olive ridge
#

so how do i make it not use a loop?

#

i basically want to make it so that meshes deform whenever another object is present

#

ive tried other methods but theyre all super buggy

leaden ice
#

anyway it's really quite unclear what effect you're going for here

#

moving a "dot" object isn't going to deform any meshes

olive ridge
# leaden ice If you want to do something once per frame, that's what Update is for
    {
        List<Vector3> List2 = new List<Vector3>();

        float circumferenceProgressPerStep = (float)1/sides;
        float TAU = 2*Mathf.PI;
        float radianProgressPerStep = circumferenceProgressPerStep*TAU;

        for (int i = 0; i < sides; i++)
        {
            float currentRadian = radianProgressPerStep * i;
            GameObject dot = Instantiate(spawnDot, transform.position + new Vector3(Mathf.Cos(currentRadian) * radius, Mathf.Sin(currentRadian) * radius,0), transform.rotation);

            float angle = Mathf.Atan2(transform.position.y, transform.position.x);
            dot.transform.rotation = Quaternion.Euler(0,0, angle);
            
            float distance1 = Vector2.Distance(transform.position, city1.position);
            float distance2 = Vector2.Distance(transform.position, city2.position);
            float distance3 = Vector2.Distance(transform.position, city3.position);

            while (radius > distance1 || radius > distance2 || radius > distance3)
            {
                dot.transform.Translate(0.1f, 0, 0, Space.Self);

                distance1 = Vector2.Distance(transform.position, city1.position);
                distance2 = Vector2.Distance(transform.position, city2.position);
                distance3 = Vector2.Distance(transform.position, city3.position);
            }
        }
        return List2;
    }
#

the dot is local to the for cycle

olive ridge
leaden ice
olive ridge
#

the vector3s is where the vertices will be

leaden ice
#

That's not an ultimate goal

#

that's an intermediate goal

#

why do you want list of vertices.

#

What is the ultimate goal here?

olive ridge
leaden ice
#

Thi sis too abstract

#

What kind of gameplay or visual effect are you going for?

olive ridge
#

i want to do something similar so as to show controlled territory on a map

leaden ice
#

to be honest if I recall Agario correctly I don't remember any kind of deformation effect

vestal arch
#

-# and uh yeah there is deformation

olive ridge
#

def gonna check it out

thin hollow
#

I have a problem - my game uses a custom light shading model (toon) shader. This makes decals incompatible with it - they get baked into the extracted lighting pass as additive objects (could be useful for faked lighting tho...).

So I thought, I'll need to make my own decal implementation, and I thought about using a boolean operation to cut out a cubic volume of mesh from the level, redo its UVs so that the texture would be projected on it from one direction, apply the decal texture, offset the vertices by a tiny amount along normals to avoid zfighting, and turn off shadow casting.

Such a solution will likely be too slow to work in real time, but does it make sense at all, or is there a simpler way of achieving the same goal of "I want to get a mesh that tightly hugs a part of the level geometry"?

sleek wharf
#

Hi guys can someone PLEASE help me? I'm going crazy, baiscally i have made after a lot of assle and weeks this EnemyAI script, which includes 2 patrolling modes (waypoints and free roam) and alot of other things.. i have a big problem i also have included a death sequence where the script choose randomly between 3 death animations and then die. but after he dies hg still rotate towards the player even after litteraly disabling the script, animator, rigid body, colliison , i tried disabling every component in the inspector of the enemy but he still rotate towards the player. please help me

Script: https://paste.mod.gg/mabbypuaaxjm/0 (dont steal, all copyright to me)

#

thank you to everyone that might help me

#

the enemy isnt influenced by any other scripts

steady bobcat
# thin hollow I have a problem - my game uses a custom light shading model (toon) shader. This...
finite falcon
#

I'm having a small issue with this code:

I really want to be able to rotate my mirror without also rotating the little popup icon,

But when I implement code to reset the icon's position and rotation, it overrides everything else and I can't rotate anything! I'd really appreciate some help :[

naive swallow
#

Also, there's no need to do GetComponent<Transform>, every class that implements GetComponent also just has .transform

#

use that instead

finite falcon
# naive swallow What calls `Interact`?

Interact is from a separate script that's just for seeing how close the player is to the object, once they're close enough, the popup appears and the player can interact with the object!

leaden ice
#

Consider using a PositionConstraint instead, or rearranging the hierarchy so that the thing that rotates is not the root parent of that object's hierarchy and the text is under a different thing than the thing that is rotating

finite falcon
#

I did consider that, but the popup has to be a child of the mirror object or else it won't work with the script :[

leaden ice
#

that is the easy part

naive swallow
#

Ah, wait, I see, you want it to stay in place, I thought your issue was that it wouldn't move

#

Yeah, you'd need it to not be a child object

finite falcon
#

Oh no it only checks the player's location every frame! Sorry, I should have explained it better- that's my bad!

finite falcon
leaden ice
#

it's really just a matter of shuffling some references around

naive swallow
finite falcon
#

I'm gonna have a quick go and see what I can do, thanks for the advice!! I'll be back in like 2 minutes UnityChanThumbsUp

#

SUCCESS!! THANKS GUYS!

#

It really was that simple, I can't believe how dumb I am notlikethis

signal moon
#

I have a very weird bug there

#

I have something that works completely fine in the editor, but not in build

#

The problem lies here: 'name' should never appear, and it doesnt in editor, as its placeholder name for major arcana

#
    {
        UpdateNextMajorArcanaText();
        roundsUntilMajorArcanaText.text = RoundsUntilMajorArcana.ToString();
    }

    private void UpdateNextMajorArcanaText()
    {
        if (MajorArcanaDraw.selectedCard != null)
        {
            string cardName = MajorArcanaDraw.selectedCard.name;
            nextMajorArcanaText.text = cardName;

            // Reset to default before assigning a new tag
            nextMajorArcanaText.tag = "Untagged"; 
            nextMajorArcanaText.tag = GetArcanaTag(cardName); 
        }
    }

    private string GetArcanaTag(string cardName)
    {
        switch (cardName)
        {
            case "The Moon":
                return "Moon";
            case "The Sun":
                return "Sun";
            case "The World":
                return "World";
            case "The Fool":
                return "Fool";
            case "The High Priestess":
                return "High_Priestess";
            default:
                return "Default_Tag"; // For unknown cases
        }
    }```
#
    {
        if (majorArcanaDeck.Count > 0)
        {
            selectedCard = majorArcanaDeck[0];
            Debug.Log($"Top card selected: {selectedCard.name}");
        }
        else
        {
            // If no cards are left in the deck, shuffle graveyard back into deck and try again
            Debug.Log("No cards left in the deck. Refilling the deck...");
            RefillDeckFromMajorArcanaGraveyard();
            UpdateSelectedCard(); // Retry updating the selected card after refill
        }
    }```
mossy snow
#

I've seen this type of bug appear if your text update code is somehow order dependent, and the script update order in a build is different than in the editor

signal moon
mossy snow
#

well you can test the theory by changing the script execution order yourself

steady bobcat
signal moon
#

nextMajorArcanaText.text

#

In the editor it looks like that

steady bobcat
#
            nextMajorArcanaText.tag = "Untagged"; 
            nextMajorArcanaText.tag = GetArcanaTag(cardName); 

why do this twice? the second can only fail with an exception and I presume it will just fuck your logic anyway

#

is this using the Gameobject name?

#

very un reliable if so as when we Instantiate() it will become "MyThingy (Clone)"

signal moon
#

public TMP_Text nextMajorArcanaText;

steady bobcat
#

No what is MajorArcanaDraw.selectedCard

signal moon
signal moon
steady bobcat
#

Right so you are using gameobject names. As I said, its a bad idea.

#

Tbh for things like this id use ScriptableObjects for data and reference them on the pieces so you can share this data (such as name) reliably

#

Tags also become pretty shit with any semi complex game

signal moon
#

i was just checking the other system that bases itself on gameobject name, and it works

#

it seems that just one script broke

silk cloak
#

I'm trying to get this to say things like 10k, 1m, 1b, etc. I have the code setup to do just that but I'm not all too familiar with Unity yet. Unsure if this is the correct area to ask this or if this should be in ui-ux. How can I get it to use the code I wrote?

#

Should this be in ui-ux?

signal moon
signal moon
#

i made this script execute first at 100 execution order

#

making it on -100 worked fine

split junco
#

I get this error log when I'm switching scenes. It's happening after the Awake and Start methods have been called.

This only happens when I am switching scenes---not when I load each of them independently. My question is, where exactly should I look to find this error?

#

The error does not provide a script location.

cosmic rain
silk cloak
# signal moon You are getting variable text right? Simply do something like if number > 1000 t...

Something like this, right? I tried it and it's not showing up how I'd like it to. Meaning, it's showing the exact same big numbers ```private string FormatNumber(double number)
{
if (number >= 1_000_000_000_000)
return (number / 1_000_000_000_000d).ToString("0.#") + "T";
else if (number >= 1_000_000_000)
return (number / 1_000_000_000d).ToString("0.#") + "B";
else if (number >= 1_000_000)
return (number / 1_000_000d).ToString("0.#") + "M";
else if (number >= 1_000)
return (number / 1_000d).ToString("0.#") + "K";
else
return number.ToString("0");
}

cosmic rain
silk cloak
lean sail
# silk cloak Something like this, right? I tried it and it's not showing up how I'd like it t...

the logic itself looks correct, I dont think your issue is here. Some beginner level debugging should've shown you this. Though i dont know if you should proceed this way anyways.
Usually games that go super high into numbers like this don't actually store stuff like 100 trillion. Is there really a need for you to store something like 1_000_000_000_001? You could just use up to 4 digits, then append a K,M,B,T, etc and keep track of which unit they're at

cosmic rain
lean sail
#

Its really just a waste to be calculating such large numbers

chrome sage
#

if i wanted a real and robust IInteractable system, is there any top tier resources on the subject? because i imagine a radius component and a isInteractableInRange function will get limiting very quickly.

lean sail
# chrome sage if i wanted a real and robust IInteractable system, is there any top tier resour...

what kind of resources are you looking for? IInteractable is an interface. You call a method through the interface -> component "interacts".
interacting is going to be extremely unique to your game so its unlikely any tutorial fully suits your needs. Nothing about it specifically requires a radius component or this isInteractableInRange function. honestly I have no clue what you mean by "real and robust" in this case

chrome sage
#

im going for a topdown rpg, i kinda want to keep it to the two mouse buttons (so i can just do 1 finger and 2 fingers on mobile) so youd click an empty tile to move the player and click a chest to open it and click an npc to walk up and talk to it and click on an enemy to enter the encounter screen.

#

id probably default to just piling all the different logic in the player controller, which i think i want to avoid.

cosmic rain
#

The only thing that I'd put on the character itself is changing the animation state(possibly retrieved from the interaction/interactable object), movment and similar stuff directly related to the character.

trim island
#

Hi, I'm trying to detect the specific terrain component under the player, but for some reason, my raycast is not hitting it. Anything wrong in my code?if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, rayDistance)) { if (hit.collider.TryGetComponent<Terrain>(out var terrain)) return terrain; }

vestal arch
#

for future reference, see below
!code

tawny elkBOT
vestal arch
#

have you tried debugging? is it perhaps just hitting itself, which does not have a Terrain component?

trim island
cosmic rain
trim island
#

Another question: I'm trying to create a tree damage system, that, at runtime, detects the nearby PAINTED trees at a certain distance and allows the player to chop them. Now I have 2 ideas about how to do this: 1) once I detect the nearby trees (withinn 3m) I replace their painted instance with a prefab, and when the player is further away, remove the prefab and add the tree instance again. This however comes with a number of challenges and optimizations that are quite complex to do. 2) I add a place holder game object in the same place as the tree instance, and use that to do all the damage calculation. When the health reaches 0, I remove the tree instance and the placeholder, and when the player goes away I only remove the placeholder.

One thing that complicates this is that unity doesn't allow to add mesh colliderst to painted trees, you must use a primitive collider. And if the tree is straight, no problem, but I have some irregular trees and I should add from 2 to 5 primitive colliders to properly map the trunk surface.

Now the question is: is there a standard/recommended way to do this? What are the main optimizations you would use?

hardy pasture
#

Should I add Assets/Resources files to gitignore? It creates those files when creating the WebGL build.

latent latch
#

Well, like are you using the resource folder? lol

#

You've got assetbundles if you need any dynamic loading otherwise

fiery steeple
#

Why it doesn't let me call the event here please ? πŸ€” And it says the event is supposed to have 2 arguments while I declared it with only 1 πŸ€”

mellow sigil
#

The null conditional operator is ?. not just a question mark

fiery steeple
somber nacelle
#

you cannot invoke an event from outside of the object that owns it

#

that's kind of the whole point of the event modifier

fiery steeple
somber nacelle
#

yeah, don't use the event keyword or just call a method that invokes the event

#

of course trying to get around the entire point of the event keyword likely means you don't need the event keyword on that delegate

fiery steeple
#

or move the event in the OnAreaEnter.cs class ?

#

Yeah switching to that class solved the issue, thanks πŸ‘

rain sonnet
#

I dont understand why docs tutorials have minimal explanations and i dont know if its just me that is dumb but often when i follow their tutorials exactly step by step they dont work and i often have to add custom code because it seems like they forgot to add some code for the tutorial to actually work. Is this common?

rain sonnet
#

Right now i am looking at character controller for netcode for entities multiplayer. Like they show how to set up both first player and third player and they say now i am able to move with "WASD", but from what i can tell theres not even an input bindings in the scripts they told me to add.

leaden ice
dusk apex
#

Maybe you should provide the link

leaden ice
#

Not seeing where it says you can move with wasd

rain sonnet
#
GitHub

Sample projects for the Unity.CharacterController package - Unity-Technologies/CharacterControllerSamples

GitHub

Sample projects for the Unity.CharacterController package - Unity-Technologies/CharacterControllerSamples

#

last link should show

leaden ice
#

Make sure there's no errors

rain sonnet
#

yeah theres no errors

#

i found their onlineFPS sample that works, so i guess i can mix those two together and use their input system

leaden ice
#

Hard to say from my phone without seeing the project in front of me

rain sonnet
hot wagon
#

Hey, im on Unity 6 and I've been trying to render the depth of the backfaces of a certain layer to a texture and I can't seem to get this to work.

#

Im using URP rendering, do I use a renderer feature for this?

leaden ice
hot wagon
#

haha, because I have tried so much πŸ˜›

leaden ice
#

I can't seem to get this to work
Seems to imply you tried something

hot wagon
#

I have been going back and forth between all AI models, to try and get something to render

#

so what I currently have is this feature:

#

and this backface shader:

Shader "Hidden/BackFaceDepth"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }

        Cull Front // This is the key part - culling front faces to render only back faces
        ZWrite On
        ZTest LEqual

        Pass
        {
            Name "BackFaceDepth"

            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float depth : TEXCOORD0;
            };

            Varyings vert(Attributes input)
            {
                Varyings output;
                output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
                output.depth = output.positionCS.z / output.positionCS.w;
                return output;
            }

            float4 frag(Varyings input) : SV_Target
            {
                // Output linear depth (not the non - linear Z buffer value)
                return float4(input.depth, 0, 0, 1);
            }
            ENDHLSL
        }
    }
}
cosmic rain
tawny elkBOT
hot wagon
#

But there is really no point in sharing my code, since its just AI crap, i just would like to understand the broad steps on how to achieve this.

cosmic rain
leaden ice
#

I'm sure it's possible with a renderer feature too but I'm not incredibly familiar with how those work

quartz folio
#

Can't you just use the render objects feature

hot wagon
#

Ill read about it, im new to URP

#

Maybe i can explain what I want to achieve; probably helps

quartz folio
#

I suppose it won't render to a texture. It's probably a more appropriate question for #archived-urp

hot wagon
#

I have created this silhouette feature in URP:

#

And it works well, but now since im working a 2.5D game, what I would like to achieve is volume aware occlusion culling, so if a sprite is in front of a mesh its back faces, I want it to render normally

#

But only if its behind the backfaces I want to render the silhouette

#

That way when e.g. my character stands on the stairs, it does not clip with the stairs:

#

(i know this is not a character but a sword, just for testing)

leaden ice
#

Wouldn't the backface thing give you a silhouette here anyway?

#

since you're behind the backfaces of the nearer part of the stair mesh?

#

I'm not convinced that's the right heuristic

hot wagon
#

hmm you could be right actually

leaden ice
#

It seems like what you want is if the object is inside the mesh, it renders on top of it, but if it's outside and occluded by the mesh, it renders as silhouette?

hot wagon
#

yes! exactly

leaden ice
#

Actually I guess you could do it if your backface depth texture was built using a LE comparison?

#

li.e. you always get the furthest backface for each pixel

#

that could make sense I think

hot wagon
#

yeah i have it:
Cull Front
ZWrite On
ZTest LEqual

#

i also don't know if it conceptually works haha πŸ˜› but in my head it did

leaden ice
#

Ok so yeah I think this makes sense in theory, I don't know that I'm expert enough to tell if that code is correct and if not how to fix it

hot wagon
leaden ice
#

probably

hot wagon
#

Thx!

stuck hatch
#

Anyone know how to create test with TestCase with IEnumerator method?

I have this test but it's always return "Method has non-void return value, but no result is expected"

    [UnityTest]
    [TestCase("Assets/BundledAsset/level1/Level 1.unity", AsyncOperationStatus.Succeeded, "", 1f)] // Level 1 - Success
    [TestCase("Assets/BundledAsset/level2/Level 2.unity", AsyncOperationStatus.Succeeded, "", 1f)] // Level 2 - Success
    [TestCase("Invalid/Scene/Path.unity", AsyncOperationStatus.Failed, "Download Error!", 0f)] // Invalid Path - Failure
    public IEnumerator HandleSceneLoadResult_ParameterizedTest(
        string sceneKey,
        AsyncOperationStatus expectedStatus,
        string expectedErrorMessage,
        float expectedSliderValue)
    {
        LogAssert.ignoreFailingMessages = true;

        // Act: Attempt to load the scene
        var handle = Addressables.LoadSceneAsync(sceneKey, LoadSceneMode.Single);

        // Wait for the scene load to complete
        while (!handle.IsDone)
            yield return null;

        // Assert the expected status
        Assert.AreEqual(expectedStatus, handle.Status, $"Expected operation to be {expectedStatus}");

        // Call the handler and update UI accordingly
        menuController.HandleSceneLoadResult(handle);

        // Assert UI behavior based on expected status and result
        Assert.AreEqual(expectedErrorMessage, menuController.downloadProgressText.text, "Text message mismatch");
        Assert.AreEqual(expectedSliderValue, menuController.downloadProgressSlider.value, "Slider value mismatch");

        yield break;
    }
thick terrace
leaden ice
hot wagon
#

Alright finally figured it out πŸ™‚ Thanks again @leaden ice

hot wagon
leaden ice
ivory elm
#

So im trying to make the camera follow the player but i dont know how... can anyone help?

vestal arch
#

have you tried googling for tutorials?

ivory elm
#

good idea i knew i would get help somehow 😁

steady bobcat
#

The answer is always cinemachine!

vestal arch
#

i mean, that's the first place you should look lol
it doesn't involve waiting for someone to answer

#

if you have specific issues after that, then you should ask for specific help

#

generic question -> generic answer
specific question -> specific answer

ivory elm
#

ok so its 2d and i just addd the camera as a child to the player which worked but now the player is shaking a bunch

rigid island
#

Also yeah just use cinemachine, it literally has a simple "Follow" slot without needing to parent anything to it

ivory elm
#

oh...

chrome sage
#

well this is embarrassing. can anyone help me figure out what it is I'm supposed to google? what i want is to condense the main camera and main gameplay to the side and have a separate status window, this status window would persist between the overworld and the encounter screen. 'split screen' seems wrong, so what is it I'm asking? bonus points if there's an easy way to switch its position too (in case i ever get left handed players....)

leaden ice
#

one is to modify your main camera's viewport so it only draws to like 80% of the screen

#

then put your UI on the remaining 20%

#

The second way would be to render the main camera to a RenderTexture, then draw the main camera view in a RawImage UI component, likewise taking up the left 80% of the screen

#

Example camera settings for the Viewport solution

chrome sage
leaden ice
#

or switch to a different camera with a different viewport

chrome sage
empty elm
#

I recently repainted some tiles in my level, and now the player is unable to detect the ground in various places with raycasts on the environment layer. collisions still work normally.
it appears to happen only in places that I newly painted (tiles that didn't exist before). I made sure everything is on the same tilemap layer, and the layer is tagged Environment.
any ideas why this could be happening? The only info I know is that the player's raycasts aren't hitting anything while standing on some sections of the ground, while it works fine on other parts

leaden ice
#

And which tiles are those parts using?

empty elm
#

they're on the foreground layer, the tilemap polygons show that they're included and the layer is correct (first screenshot).
And the collisions work which is the weird part, but raycasts can't detect it

#

and as I mentioned they are all tiles that were empty space before, and I newly painted. There are other tiles that are newly painted, but those work fine

leaden ice