#archived-code-general
1 messages Β· Page 447 of 1
you should test in an empty project and submit a bug report if you can reproduce it there
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 ?
you're using PlayerInput and trying to mix that with InputActionReference
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
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...
this tutorial is leading you astray
there is no reason to have the PlayerInput component with this approach
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
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.
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
yeah i watched around 5 videos .. and everyone shows a different way
better way would be reading the unity docs.. probably.. right ?
its just Polling, Events and Broadcast Messages
The docs also list all of the ways to do it
awesome site lol the first API I learned to use in c#
Okay π damn .. i just need an easy way for the start xD i don't want to learn it with the old input system the Course show..
put ty anyways! I'll try other ways to get to the goal.
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..
a force calculation for what
what's the goal
the force calculation is as always: f = ma
Got it Working an easy way π
yes, i said i used AddForce but it is odd
what's odd about it?
just fyi Translate ignores walls and such so idk if you're trying to do character being stopped by obstacles
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)
If you are adding the force every frame, then yes it's going to start going very fast.
especially with Impulse
you might be using it incorrectly , show code
did you set mass really low?
On
and you'll have to explain what "looks glitchy" means exactly if you want help with that part.
ONE
im just following the Unity Course and they do it with Translate in the video ^^ just followin it
just wanted to do it directly with the new input system
rn
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ultimately - explain what you're actually trying to accomplish here, and show your code if you want better help
ahh you're talking about the runner demo ? yeah that always struck me odd...
but that one ig doesnt matter because hitting an obstacle does trigger game over and not meant to stop / slide player along walls
something that looks good
the junior pathway prototype 2 where they shoot pizza at mooses π
oh cool never seen that one, sounds like they added some new stuff
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
but it didnt feel right to learn it with Input.GetAxis ^^
Oh cool. Yeah never seen this one before π
///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
IMO its always good to learn the old input system too, just because older tutorials use it, and you might know exactly how to convert after
show the full code. Literally anything could be inside getThrowForce.
And none of this is using AddForce like you said
changed it
still same problem
i used the old one in Mission One (Or two?) (The Car & the plane project) ^^
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
only the last calculation is odd, the rest are tested and work fine, π
And i don't think you would like me to send you 3 classes just to look for 2 variables, π
And what were the methodologies for testing them that resulted in "working fine"?
what is "the last calculation"?
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
And what is the actual problem anyway? Did we ever get more detail than "is odd"
nope
better if i send my whole project? π
a video would also be nice..
"odd" is completely not actionable
no it's better if you just explain to us what the hell is wrong
and show the code that was asked for
You need to explain what is currently happening, and what you expect to be happening
i guess his projectile is too fast .. as much i understood ?!
see? he gets it
"is odd" doesn't explain that
Okay, so, make the speed less
Whatever magic sauce the getThrowForce function has should be less so
there could be magic sauce inside of getThrowForce or directionToMouse()
as well as the calculation of whatever throwForce is and straightness
try to divide you straightness by 10 if it defines the speed (as the comment shows)
Guys I'm new heare where and what sld i start with ?
maybe send the values here of
dir
getThrowForce
straightness
!learn π
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
750!!!?? Daymmm
750+ hours yes, All Free.. obv you don't have to do them all..
Will i learn everything? In that 750 hours?
lol
I've been using Unity for 12+ years and I'm still learning.
they put it there "for fun"
Huh 750 ain't enough? Like
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
learning everything is impossible
there's always more to learn
start with the pathways then go from there
even if you learn everything that exists now, there will be new stuff coming out faster than you can learn it
you'll learn the basics.. started 2 Days ago
Okay like what do you reccomend like im a begginer sld i jus start with unreal engine or sld i do unity instead?
dev is a never ending process of learning
Ouhhhhhhh ok ok
I see
But like it's soo complex
Sld i start from 2d or 3d!
Unreal Engine is harder to learn imo
anything in the beginning is complex..
Doesn't really matter
Fr fr
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
whichever one you want to make
once you learnt the basics it doesn't look as "Scary" or complicated
Hmm I'll start with 3d
neither is harder than the other, they're just a different set of skills
3d I'll start
Yepoo understood
3D imo is easier but its just personal opinion
So like in that 750 hours I'll learn the basics?
Sld i learn blender too?
you are also meant to learn c# outside of the Unity learn site..
Learning isn't, like a binary switch. You don't go from "not learned" to "learned" in a discrete time span
it has good stuff for c# relating to Unity but you still need to learn traditional c#
no, that 750 covers a lot of topics
2d and 3d, but also vr, ar, simulations, etc, stuff you might not (probably don't) need for every project
Can't i choose my own programming lang?
no
Can you like tell what i sld learn? In that
You can, as long as you choose C#
the ones you want to make or use
ah, the ford choice
it's divided in Missions.. start from Mission 1
So i sld only use c# but idk nothing in c# i only know c and c++
Best get learning
if you know C++ then c# should be a cakewalk..
that's already a big step
programming knowledge is quite transferrable between languages
Oh oh ok ok
Aytt then imma start from tomorrow
C# is very similiar to c++... duh.. you should be ok
https://learn.unity.com/pathway/unity-essentials
Heres the Essentials Path
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Ouhhhhhhh ayttt
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yea this one
yes start with the pathway as was suggested above
@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
Ok ok ok
do Essentials -> Junior Programming, and then go from there
Uhuhhh interstingggg
Okokkk
Daym y'all are so helpful
Thnx y'all
that's our job description π
welcome to Unity π
if you want to use blender, yes
For like making 3d models and shi?
you can use premade assets that are free
But that feels like stealing
if you want to create your own models .. i mean .. there are more 3D software out there.. but blender is free.. and nice ..
but if you want to learn 3d modeling thats up to you
If you want to color stuff with crayola crayons, you have to learn to use crayola crayons
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
Yea yea i did make the doughnut once it came out well
if someone publishes their own assets for free use, that's for the community to use
you're part of the community, you're allowed to use them
its generally a good idea to use placeholders as well, so you can focus 100% on learning coding and all that, learning too much at once can be overwhelming
Yeaaaaaa wise man Once said
I'm personally using Blender for the 3D model + Substance Painter for the Textures
Yea yea
Hmm hmm hmm is there any good place to find assets?
Like 3d models
the asset store
Got ittt
THE NAME ITSELF IS ASSET STORE?????
LMFAOO
Daymmm never knew that
Y'all so smart af
i mean... the app store is called the app store
Daym its paid?
some of them are
50 DOLLARS?
Ngl they look good
you can filter the price to free..
Yea yea
that's why they're expensive
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
(unless your focus is about making assets, that's fine too, but focus on one thing at a time)
Also theres the new one .. fab.com
Epic trying to cash in on them unity assets
as we know epic .. lol
Why
Well well well epic
They always
Unreal store was a flop lets admit it..
as if they wouldn't make enought money by dropping a new fortnite skin a day haha
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.
I'm pretty bad at rotations myself lol but one thing you can start with is having the normal of the wall you're on via raycasts to get it. have you tried starting with that ?
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
yes, I have the normal of the wall already. (needed it for some other shits too)
umm is it normal that i have to close vs code for my code to compile?
no
no its not normal
by "close vs code" do you actually mean just tab back into unity? because that is normal
does anyone here know how to fix that it's driving me insane π
no i literally have to close vs code
like my changes show up in the editor but they won't actually compile until i close vs code
wdym changes show up in editor ?
the inspector in the unity editor
is your game running while this is happening?
no
Tbh i dont fully understand what you are doing but you can produce a rotation from a directional vector if you are able to project the move dir along the wall.
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
you should try to use quaternions more vs euler angles (they are easy to construct from eulers anyway). Quaternions can be "combined" too via *
im on linux if that matters
so my changes show up here as im editing in vs code but won't compile until i close vs code
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?
i have autosave enabled
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.
i've tried turning it off and manually saving as well
the file changes show up in the inspector though which is what confuses me
Then i bet its some linux bullshit
yeah i thought so too
ive tried looking it up but i don't think anyone else has this problem π
did you disable asset database refresh?
and you haven't ever called this API right? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetDatabase.DisallowAutoRefresh.html
no
wait hol up ill send a video
WTF WHY IS IT WORKING NOW
OHHHHHH I KNOW THE CAUSE
ok so what caused it is me using the workspace view to change tabs instead of the normal alt tab
Wow thats kinda dumb but perhaps the editor isnt notified correctly of it regaining focus so it never recompiles?
i was legit stuck on this for an embarrasingly long time
open a bug report so it can get fixed
it's sad that unity's learning platform has a lot tutorials where the videos are broken.. makes it all harder
like which ones?
uhm okay.. kinda strange.. not a single video is working anymore.. lol maybe it my browsers problem ..
For example i'm here now .. ^^
https://learn.unity.com/pathway/junior-programmer/unit/basic-gameplay/tutorial/67559e90edbc2a0eaf59bd44?version=6
Did the last 5 Lessons without videos because of that error
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
i can confirm that same issue is happening in both firefox and chrome, likely an issue on unity's end
it was really relaxing to watch how the stuff is done π hm.. maybe it'll work tomorrow.. i should take a break
maybe .. yes
yeah, the issue is likely temporary. but i'd recommend submitting a bug report or support ticket or whatever
π«‘ good idea. but good to know the problem's not my pc's fault
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.
preumably the max lifetime of the projectile would do it?
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.
ok that seems to have done it
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!
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 π
What's the goal here? This interface has no defined members so it doesn't do much other than act as a marker.
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);
}
}
Solutions like this already exist just using a regular base class though
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
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
Does DontDestroyOnLoad affect the parent-child relationship of objects?
No
might be a good idea to log more things
like cardContainer.childCount
Sure, one sec
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.
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
Good to know
It was another object
There was a duplicate of the gui
Thank you for helping me find that
I want to get dictionary-like behaviour in a scriptable object, but unity obviously cant serialize an actual dictionary. Any tips?
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
[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.
so basically that first option there yeah
problem is that I actually work with Domain Reload off typically, and OnEnable doesn't get called on Play Mode for scriptableobjects without it.
not familiar with SOs, so can't help with that, sorry
could try the 2nd option i listed, i suppose
Maybe I just also set the cache in OnValidate?
You could init it lazyliy, or just not do it in the SO. Let it keep only the serialized list/array and keep the dictionary in some kind of manager.
You could also maybe use initialize on load attribute
Ah, that's only available in the editor.
iirc using both onenable and onvalidate ends up doing all the right times?
oh wait for this is ISerializationCallbacks not the move?
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.
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
Not sure what you mean by a serialization callback.
This only implements on before and after serialize. If you want to use these callbacks, then yes,you need to implement the interface. But on enable and on validate don't require it.
yeah im suggesting to use this instead
Aah. You can do that, yes.
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?
To cancel an async function is to stop it early. This is usually done via cancellation tokens
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?
Well its up to you but it can either revert back or jump to the end?
Its your transition logic after all
Might want to explain what you mean by a "transition"
Well... The function I made does "Play till finish"
Is it an animator state transition? A scene transition? Something else?
That's an overloaded function that allows you to crossfade and then play till finish
Are you referring to a specific unity API?
Crossfade what? Are we talking about animations?
I'm making an abstraction over Animator
Okay. Then it's up to you to decide what your methods do on cancelation.
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
An animator transition actually means that the next state is already playing.
The previous state weight fades out during the transition
I think that I'll add two parts to it...
- 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.
- 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.
AttachExternalCancellationTokenis a feature from UniTask, and simply neglects the outcome and moves on
Does this seem sane? xD
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
Externally providing a CancellationToken doesn't seem to make much sense here since in general the only sensical use case I can think of using CancellationTokens for externally is to skip waiting for the animation to end (For example when the player got staggered) without intercepting the animation itself
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
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.
Try to migrate to the newer toon shading package: https://docs.unity3d.com/Packages/com.unity.toonshader@0.11/manual/index.html
https://docs.unity3d.com/Packages/com.unity.toonshader@0.11/manual/TessellationLegacy.html
for compatibility reasons I am sticking to UCTS 2.9 for now, but even UTS 3/0 doesnt seem to have height built in.
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
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.
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?
input system questions go in #π±οΈβinput-system
and don't ask to ask, explain what your question/issue is there, along with any errors or warnings or logs you have
At what interval does while get executed? Same as update?
while loops are not special in any way, they run until completion just like any other loop. they do not get executed at intervals
would this even work then?
that entire loop executes within a single frame
ahhhh well thats my problem then
if that is in Update are you sure you don't want it to just be an if statement?
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?
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
Ohhh i forgot about coroutines, thank you very much!
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
Mate, some day I wanna know as much as you do about unity code.... thanks again!
You could just make an update method, and have your MonoBehaviour call these objects update methods within its own to basically "pass through" the update timer to them
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.
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?
I got a warning, Give me a sec, I need to reproduce it
I want to only have a select few the timers run at any given moment
so whatever is being newed on line 189 inherits from MonoBehaviour so you cannot new it
how else would i do this then?
also is this not what the startTimer bool is for? your while loop gets turned into an if statement and that method is invoked from a MonoBehaviour's Update method and bam it's working as expected
Why does Note inherit MonoBehaviour?
If I don't inherit MB I can not get the Update function in the Note class, but I am struggling to create a timer inside the Note class without it.
ohhh that might be a way, I will try this
that's what digi was suggesting
Okay I am just stupid then, i'm sorry
you cannot new a MonoBehaviour, best you could do is either create an instance of a GameObject with new then AddComponent<Note> or just use Object.Instantiate to instantiate a prefab that contains that Note component
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
this is what I will try
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
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.
The usual pattern would be: cs var materials = stationTrackerRenderers[i].materials; materials[0] = trackerMaterials[i]; stationTrackerRenderers[i].materials = materials;where you'd only get a copy of the materials collection
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.
I missed that part about replacing the whole array really.
That's fine. Thanks for the help.
I think its because the property goes to native code for get and set (so requires a write back to do anything)
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
There is a cost so consider batching as much assignments as possible before reassigning back to the renderer materials collection
I only have to change 1 material on the renderer but I have 7 renderers to change in my for loop
So not sure if I can optimize that somehow
You can use this variant that lets you re use 1 list for many: https://docs.unity3d.com/ScriptReference/Renderer.GetMaterials.html
So if given a smart size to begin it should be better alloc wise
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]);
}
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
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();
}
Remember to clear it before each new use and use SetMaterials to avoid wasting the whole point of this π
there's StreamingAssets which I believe can be written to on most platforms, otherwise I would recommend writing the data to persistentDataPath and just load the data from resources if it doesn't already exist at persistentDataPath
for (int i = 0; i < stationTrackerRenderers.Length; i++)
{
UpdateMaterial(0, materials, stationTrackerRenderers[i], trackerMaterials[i]);
materials.Clear();
}
That should do it then, I think
Also don't crosspost
In Unity Localization, how do you add a
is this normal to take this long just for a cube that rotates and changes his scale & position?
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
oops sry.. okay π took me 14 minutes for that build.. won't imagine how much time it takes for a bigger project
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 ?
You can use Awaitable or UniTask to do this quite easily
using Awaitable won't require another package so would be the easiest (assuming you are on unity 6 or higher)
I See. So I make the receiving method Awaitable then switch the thread there ?
Yes. Check the example here on how to use an async method correctly with this: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Awaitable.MainThreadAsync.html
UniTask has a similar function to await and go to the main thread if you prefer it or are on 2022 and earlier.
yeah this looks promising, thanks!
Np. I use the UniTask variant with ad watch callbacks as they are often all over the place thread wise
quick question about Awaitable. How do you handle the fact that my function wants an Action delegate ?
invoke the Awaitable method from the method that the event invokes
Ohh that makes sense , thanks!
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
@somber nacelle & @steady bobcat worked great! thanks again
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.
You may need a rigid body
they both have a rigid body
have you gone through the steps in the link i sent yet?
yes and all it leads to is the unity docs page of OnTriggerEnter2D
oh wait i see more
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
Hey, so I got a wall running thing going, but I have no clue how to get my movement directions to align with the wall you are running on.
When I am on the ground, I just take the Y rotation of the head and apply that to an empty gameObject to use as a movement direction index. But I have not been able to do a similar thing for the wall run.
https://gyazo.com/b98027c03bc0053e6c0847e9597d278a
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
If its just to do the head bob properly you can rotate the rotation by the wall normal "look rotation"
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
Im not 100% but I think you can use this and give the wall normal as up and then rotate your bob by this:
transform.rotation = Quaternion.Euler(0f, 15f, 0f) * Quaternion.LookRotation(transform.forward, surfaceNormal);
The point I hope to convey is rotating the bob using the wall normal so its relative to that
what head bob??
Hmm i miss understood, you mentioned head rotation
Then try making Plane with the surface normal to restrict your movement to be on that plane: https://docs.unity3d.com/ScriptReference/Plane.ClosestPointOnPlane.html @lucid brook
there is also a function to raycast and get the hit dist which can be used to get the hit point on the plane.
I, don't think I understand what that means....

Do you know what a surface normal is?
yes, I already use the normal of the wall for some other stuff
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);
}
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.
I still don't think I fully understand it but from what I do understand I don't think it is what I need. I could have probably done a better job explaining my problem.
If you had a gameobject per sand piece your performace would be UTTER SHIT.
How you describe your movement already sounds strange tbh. Can you share some code? Using y euler rot sounds bizzare
my code might be very bizarre, lol. but yeah let me spend a bit of time typing up a better message
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
You can easily use a compute shader to update some texture you show on the whole screen.
And for other situations where you may have many thousands of objects to simulate you can use Entities https://docs.unity3d.com/Packages/com.unity.entities@1.4/manual/index.html
Thank you, will look into this
Though i see no good reason to have an entity per sand particle as that seems needless
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
yea i would probably go this route too. Entities and ECS could potentially be a good fit still as its optimised for such workflows
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...
So you use another Transform that is rotated to match the camera world Y rot to then get a "forward" direction?
yes
you can still use this "forward" but project on a plane for the wall to keep the movement affixed on the wall
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.
why would that be? have you tried it?
the point is to move them on the wall plane instead of world XZ
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.
if its world y rot cant they still walk off the wall?
How do you mean? Like the wall being to your left and you walk to the right?
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
you could have it be a child but counterrotate to stay in the same orientation
Isn't it workaround? Editor rotates, then I rotate e.t.c. Why isn't there way to make rotation independent...
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
I see, thank you
There are components provided by unity to do stuff like this: https://docs.unity3d.com/Manual/class-ParentConstraint.html
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?
why not the class is a POCO you're fine with a constructor
It's fine to have a constructor, even if it'll be serialized by Unity and usually populated in the inspector?
isn't constructor what unity runs anyway when poco instance is created in the inspector ?
you can probably have another constructor with params if you want to create it with specific values? or make an Init method?
Is there a difference when calling isGrounded after or before moving the character controller in the update method?
Thank you for it. But I don't get what is wrong with me. I have tried enable and disable "freeze rotation axes", but it has no effect. Text follows and rotates with entity
there are position only and rotation only components too, the doc page shows the others on the left side
I would have expected locking rotation to stop that rotating though π€
its still a child of the object π
You need a script to keep setting its world rotation to Quaternion.Identity each frame
I am sorry, I am being stupid
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
Okey, I made it just with script. Thanks anyway
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?
use Debug.Log() to log both values
oh, GameObject.GetScene is returning null an invalid scene :( Why?
OnSceneClosing is called before the scene closes:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SceneManagement.EditorSceneManager-sceneClosing.html
probably GetInstanceID isn't the value you expect it to be
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.
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?
Aren't you getting the instance ID of the component here instead of the GameObject?
Also couldn't you just do gameObject.scene?
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.
The API you were using specifically checks for the scene of a GameObject.
Getting the scene of the component, how would that be different from the GameObject it's attached to?
Oops.
Also im not sure, could it be different?? If not whats the get instance id for?
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
Components are attached to GameObjects. They cannot magically live in a different scene than the GameObject they are attached to.
As for instance IDs every UnityEngine.Object has an instance id.
That's what links it to the native instance
@shell scarab
the script is attatched to the gameobject as a component
Make sure you don't ignore the channels parameter. Have you read this? https://docs.unity3d.com/6000.1/Documentation/ScriptReference/MonoBehaviour.OnAudioFilterRead.html
Sorry that message was replied to the wrong person
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.
Does GameObject have children? I bet what you want is on the Transform
The transform also shows a child count of 0:
you have the wrong one
this one?
thanks a ton. I'll double check
Thank you so much for pointing that out!! The feeling of being able to move forward again is very liberating.
I have read it, but im still not fully certain on how to setup for my purposes, i will try again tomorrow
Find in start π , add null check
I can not change name "con" evenif there are no same name in folder
CON is not a valid file name in windows (there are some reserved names that cannot be used)
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, COMΒΉ, COMΒ², COMΒ³, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, LPTΒΉ, LPTΒ², and LPTΒ³
https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
I use mac
then may be unity enforcing this for compatibility on win too
just do _con or something similar
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?
Why is this happening to the hand if the IK target (left hand) is parented to the flashlight? Shouldn't it never move its position relative to the flashlight?
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
did you write it incorrectly? public override string OrderKey => "foobar";
is OrderKey in the interface? me confuse
i believe so ye
then doesnt need to override to implement the interface
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
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
I already use an abstract class down the line, but I needed it to be in the interface. It works now so it's fine
should be a combination of both then
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>?
The two approaches have some tradeoffs:
- Reading/writing one big file is generally faster than the equivalent of many small files.
- If you only need to read/write one small portion of the data (eg only one character in your case) and it's isolated to one file, then you wouldn't need to pay the price of the other data.
It will probably come down to how often you update all characters vs how often you update just some characters.
JSON isn't fast at a large scale so many files may be better when things are large
at the point where you need multiple files, you will likely be at a point where using a proper database makes sense (differential updates, read/write performance, integrity)
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
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
there is stuff like Realm, which inherently avoids that step https://www.mongodb.com/docs/realm-sdks/dotnet/latest/ (unfortunately it was bought my Mongo and later abandoned)
There are so many it's not even funny
EFCore's SQLite adapter works fine but i never checked if it support netstandard and anything other than desktop platforms
Uh. Someone made a package https://github.com/IvanMurzak/Unity-EFCore-SQLite
Tho it seems to be limited
EFCore removes the βlightβ from SQLite π₯Έ
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...
(Unity probably enforces this even on other platforms for compatibility)
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.
sounds like prefabs could simplify that workflow
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
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);
do you have a dir titled "Items" in the root directory and not the asset folder that you place sprites in
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 " "
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.
but I test it in the selector manually as well, and it doesn't work there?
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.
didn't work sadly, thanks tho π I get your point and I have tested it earlier :\
do you perhaps also need to escape the path separators?
if so that'd be 4 \ per path separator
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 π
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
an easy way would be to put the collider on a child of the object and instantiate it as a child of the second object
there's no easy way to instantiate a single component
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.
Reflection is not a good way, no.
is there a better way to do the instantiating single components, or is it not worth it in any way.
there is not a better way
Unity could provide one by giving us more granular access to their serializer, but they haven't.
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 π€
if i could extend colliders, then i could also do it that way.
Hm... I cant seem to figure it out even after reading it. The channel parameter is given when the OnAudioFilterRead triggers?
Then I need to scan the 2048 long array of data of each channel to get an outputs?
the array has all the data in it for all channels
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
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?
i think position 500 would be the 251st element for channel 0
there would be no channel 2
just 0 and 1
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
you checked all the samples?
I did check a few, not all of them though...
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}");```
ok used that, and yea its all zero
THat's odd...
huh...
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
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?
Hard to say without more context. Is it a skinned mesh renderer perhaps?
@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?
Aabb are world aligned, so if your mesh is rotated, they might need to grow for it to fit.
Yeah but I can't figure out how a ring/sphere could stretch the bounds
It's a box. Not a ring or a sphere
Yeah, but the box is made to contain a sphere, so it should always be the same size
Perhaps it's not just a sphere then. Maybe there's a rogue vertex somewhere making it not symmetrical
I assumed that as well, but I iterated through verts and really seems like 1 is the max value
Then I'm not sure.
Thanks anyway
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.
You're absolutely right for the ring. Maybe the bug is there and I'm just having issues visualizing it. Just iterated through all the verts checking their magnitude and the biggest value is 1. I think that means that it couldn't possibly stretch an AABB to 2.83 no matter the rotation
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
What value are we talking about?
so thats why its projected like a cube
Is it the magnitude of the box size?
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
Perhaps. Maybe look at the meshrenderer.bounds docs page. It has an example of how to visualize them.
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!
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?
Share the full script
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
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
Bloom just operates on the relative brightness of your objects
The issue is probably that the UI is rendered after post processing(bloom)
If you make it render before it, it might work.
That's fair, though there are TextMeshPro 3D objects.
Yeah,I'm not sure where in the frame these are rendered.
You can check with the frame debugger
they seem to be rendered like any old transparent mesh
Okay. And they are not affected by bloom in your case?
they are, it's just there isn't an HDR color control availabe for TextMeshPro anymore.
so I can't control the amount other than with the global intensity value
Ah, I see. I guess you'll need to modify the shader to be able to expose and HDR color.
Sadge, but oh well.
HDR was avialable until Unity 6 it seems. Likely because text was usually in the UI, and HDR color wouldn't match what was seen in it's typical case.
Interesting. Are you sure it was unity version and not the active render pipeline or something?
there's an attribute to tell it to use HDR color I think?
Well I've got a version of Unity 2023.1 open, and a version of Unity 6 open, aaaaaand... ya.
Color in the material is no longer HDR.
Reproduction steps: 1. Make sure you have HDR enabled 2. Open the attached βrepro_IN-88688β project 3. Select the βAssets/TextMesh P...
@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?
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?
whats not working
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
what is not stopping
the game my dude
its working when i open my esc menu
but not with this different script
what is not stopping
time
What do you consider to be time
Yeah what exactly is happening in the game?
Because it might or might not be tied to time scale
the process of change
i want to stop animations, character movement and enemy movement
just how you see in vampire survivors when the level up UI shows up
why are you all phylosophical
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
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
Ok but I am not you and I need to be aware of those expectations, hence the questions
Have you first checked that the timescale actually stays at 0 during the period
oh havent tried
lemme check
debugged timeScale and yea it does say 0
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
(and also still worth specifying what character and enemy movement mean)
first inside the function but then decided in the Update() for more accurate info
its only going to 0 for a frame apparently
then goes back to 1
yup
is it okay to time.Timescale = 0f in the update function?
going every frame
i mean its fine but it doesn't do anything
the game resumes, enemies start shooting again and chasing you
you misread that
Thats a bandaid, better to just not change it to 1 when you dont want to
ill make a PauseManager for this
so i only change the timeScale in one place
In the editor it says
"String based property lookup is inefficient"
animator.SetFloat("Speed", moveDir.x);
is there a better way?
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
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,
}```
i use struct and job because i have a lot of Humans so ScriptableObject is expensive
I mean in that case the int could be an index pointing to various things
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
Well, how is making it expandable gonna help with that?
Wouldn't it be the same as adding new values manually?
i am looking to make the property easier to work with, like using int as id from struct array instead of enum, or write a editor tool to make sure the enum and the dictionary match
Well, then do that. An editor tools sounds like a good start.
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.
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
SpriteRenderer is often used with sprite atlasses, textures that contain several sprites. If it uses a different texture, I'm pretty sure that would be 2 separate materials( or at least draw calls).
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
it work if u enable instancing for the shader and also get the 'material name(instance)' in the material component at runtime
the MaterialProperyBlock also work fine
Sprite renderer produces a mesh with uvs to show only the sprite on the texture. Its easy to do the same on your own meshes by making the UVS with a shared texture.
It also uses vertex colours for the tint
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)
ui document or canvas (screen space overlay?)?
Nvm, while making an example I discovered the issue. Wow, I've struggled with this the whole day before deciding to ask around π
rubber duck moment
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!
not sure myself but any reason for it not to be screen space overlay?
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
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?
{
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
If any of those are true, you'll never escape the while loop - infinite loop
you're only moving dot and then comparing distances for transform
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
anyway there's no reason for this to be a loop... yeah exactly this^
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.
Yep just set it to whatever you'd like
Physics.gravity = whatever;
the point of it is to make it so that a dot moves back whenever another object is in the radius
Is it really that easy lol
yep Β―_(γ)_/Β―
One line of code
why wouldn't it be?
Is physics.gravity accessible
thats the point
I don't have my pc rn so can't check
Why would I tell you that if it wasn't?
then obviously the loop will never end
it moves the dot away from another object and recalculated their distance
I was expecting it to be difficult
Okk
but you're calculating the distance to the object the script is on, not the dot
so moving the dot won't change that distance at all
anyway read the rest of what we wrote - the loop makes no sense even if you didn't have that error
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
If you want to do something once per frame, that's what Update is for
anyway it's really quite unclear what effect you're going for here
moving a "dot" object isn't going to deform any meshes
{
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
the dots position is where the vertices will be made
what is the ultimate goal of all of this
to spawn a dot and add its position to the vector3 list
the vector3s is where the vertices will be
That's not an ultimate goal
that's an intermediate goal
why do you want list of vertices.
What is the ultimate goal here?
so that the mesh gets spawned
you know how whenever spheres in agario touch they deform?
i want to do something similar so as to show controlled territory on a map
For something like that my mind jumps to a Voronoi style shader effect. Distantly related example: https://www.youtube.com/watch?v=dw7Krz6M9ps
A Voronoi shader with transform position inputs
to be honest if I recall Agario correctly I don't remember any kind of deformation effect
-# gotta validate that assumption, go play rn
-# and uh yeah there is deformation
ok this is huge
def gonna check it out
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"?
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)
A tool for sharing your source code with the world!
thank you to everyone that might help me
the enemy isnt influenced by any other scripts
Found this cool tutorial: https://www.ronja-tutorials.com/post/054-unlit-dynamic-decals/
Often when doing VFX you want stuff to stick to the floor. Even when that floor is uneven. Or decals to make existing geometry more interresting, or you want blob shadows on uneven floor, or some other use-cases in the same direction.
(note: I used the free βNature Starter Kit 2β from the Unity Asset store throughout this tutorial)
Unity h...
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 :[
What calls Interact?
Also, there's no need to do GetComponent<Transform>, every class that implements GetComponent also just has .transform
use that instead
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!
If you don't want an object to inherit the position and rotation of another object, you should not make it a child of that object
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
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 :[
you will have to refactor the script somewhat
that is the easy part
If that function is called every frame, it's going to set the position and rotation every frame
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
Oh no it only checks the player's location every frame! Sorry, I should have explained it better- that's my bad!
Dang it, I feel like that could take me a while to redo 
it's really just a matter of shuffling some references around
Just make it a public field and drag it in
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 
SUCCESS!! THANKS GUYS!
It really was that simple, I can't believe how dumb I am 
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
}
}```
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
I see, but i don't know how to check and make build same as editor. The whole functionality of drawing cards at the start of the turns isnt working, so i assume the whole script went down
well you can test the theory by changing the script execution order yourself
Do you mean the part that says "6:Name" ? What is the text variable name so we actually understand the code π
ooups, sorry
nextMajorArcanaText.text
In the editor it looks like that
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)"
public TMP_Text nextMajorArcanaText;
No what is MajorArcanaDraw.selectedCard
I honestly wrote it 3 months ago, i don't remember why this particular part was there, it might be a mistake
public static Transform selectedCard;
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
i was just checking the other system that bases itself on gameobject name, and it works
it seems that just one script broke
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?
You are getting variable text right? Simply do something like if number > 1000 then :1000 + k
i recreated the issue
i made this script execute first at 100 execution order
making it on -100 worked fine
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.
Are there any details/callstack to these errors?
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");
}
What doesn't work? You'll need to provide a better explanation of the issue.
I want it to show "1k" for 1,000, 1m for 1,000,000 and so on. It's still showing the whole number of gems I have.
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
How are you using the method?
Its really just a waste to be calculating such large numbers
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.
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
ya its a stupid question. what i NEED to do is keep trying it out on new interactables and 'feeling' if its responsive and produces an expected result. and seeing what happens when i run into more then one IInteractable in its radius....
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.
Sounds like something that should be handled by the interactable object itself.
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.
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; }
for future reference, see below
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
have you tried debugging? is it perhaps just hitting itself, which does not have a Terrain component?
Yes, the raycast doesn't hit anything. It doesn't enter the first if
- Visualize the ray with debug rays.
- If the ray originate within the terrain(or very close to it), it would not detect it. Maybe try shooting it from a bit higher.
That did the trick, thanks!
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?
Should I add Assets/Resources files to gitignore? It creates those files when creating the WebGL build.
Well, like are you using the resource folder? lol
You've got assetbundles if you need any dynamic loading otherwise
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 π€
The null conditional operator is ?. not just a question mark
same issue still π€
you cannot invoke an event from outside of the object that owns it
that's kind of the whole point of the event modifier
is there a way around that ?
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
or move the event in the OnAreaEnter.cs class ?
Yeah switching to that class solved the issue, thanks π
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?
Which doc in particular?
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.
Most likely you're missing something
Maybe you should provide the link
Not seeing where it says you can move with wasd
I also tried this one at first:
https://docs.unity3d.com/Packages/com.unity.charactercontroller@1.0/manual/get-started-third-person.html
because i followed this tutorial:
https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/tutorial.md
and under it says i should be able to move:
https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-charactersetup.md
last link should show
Did you have your console window open?
Make sure there's no errors
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
Hard to say from my phone without seeing the project in front of me
alright, thanks anyway
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?
Why don't you show what you've tried?
haha, because I have tried so much π
I can't seem to get this to work
Seems to imply you tried something
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
}
}
}
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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.
This is correct to a degree imho.
I mean the basic approach could just be:
- set up a camera with the culling mask set to just that layer
- Have the objects all exist with the backface shader
- Render that camera to a RenderTexture
I'm sure it's possible with a renderer feature too but I'm not incredibly familiar with how those work
Can't you just use the render objects feature
Ill read about it, im new to URP
Maybe i can explain what I want to achieve; probably helps
I suppose it won't render to a texture. It's probably a more appropriate question for #archived-urp
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)
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
hmm you could be right actually
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?
yes! exactly
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
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
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
so my better bet is to go to #archived-urp
Thx!
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;
}
it's been a minute since i did this but i think you might need to do it differently for [UnityTest] tests, the docs say to use ValueSource instead in this case: https://docs.unity3d.com/Packages/com.unity.test-framework@1.4/manual/course/test-cases.html
That error is coming from your [TestCase] annotation I'm pretty sure
Alright finally figured it out π Thanks again @leaden ice
So im trying to make the camera follow the player but i dont know how... can anyone help?
have you tried googling for tutorials?
good idea i knew i would get help somehow π
The answer is always cinemachine!
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
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
camera as child of player should not be affecting anything.. you have to show more info on the setup.
Also yeah just use cinemachine, it literally has a simple "Follow" slot without needing to parent anything to it
oh...
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....)
THere's two main ways to do this
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
ah, thank you. the viewport one seems like the simplest, say I used the viewport solution, would i be able to easily switch back to 100% of the screen for when i would want to show cutscenes?
sure you'd just have to change the viewport again
or switch to a different camera with a different viewport
and there's PLENTY of tuts on camera switching, so I know what I want now, thanks again.
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
Which parts don't work?
And which tiles are those parts using?
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
Can you show your raycast code?