#archived-code-general
1 messages · Page 229 of 1
i'll tell you what the game is
it's like a game where you gather resources by clicking, similar to cookie clicker
but you can travel across a map, buy and trade stuff, and improve your garden
then you can fight bosses
the code i'm making is for the player fighting bosses in an arena
then I would avoid wall jump mechanics
so i want it to be as fluid as possible to be a stark contrast from the boring clicker
no because the idea was
like in mario, you could wall jump onto their heads
which could damage them
wall jumping is always on the higher end of skill of platforming. if your game isn’t primarily a platformer, you should avoid it like the plague
oh?
i have lots of experience in mario maker. the first mandatory wall jump you add to a level immediately filters out all the very casual players
ohhhh
no that's the funny part
i'm trying to make my game thrive off of the idea
that you can either farm and get to the end
like stardew valley
or for people who enjoy mario like games
or advanced fighting
that doesn’t sound like a very good idea
they can take that path
how come?
no but it all combines
like hypixel skyblock in minecraft
you can either farm shit
or you can go ahead and beat up things
that's why the community is so large
for instance my friend prefers to grow stuff
while i'd prefer to beat things
#archived-game-design if you want to discuss your game ideas. This is a coding channel.
whenever you blend genres, you need to know what you are doing. and from this discussion, I do not think you have the mastery to pull it off from a game design perspective
sorry
ah
last thing I’ll say here is; It’s nothing personal. hybrid genre games can work. but you need to be a masterful level/game designer to pull it off. A high degree of experience is mandatory. Even if it doesn’t seem like it
thank you, I'll change my idea then.
idk if this is the right place to ask but i've had this issue on only my laptop for aaagges now
my desktop it doesn't happen and the other programmer on the project it doesn't happen to
but if it can happen on my pretty decent laptop i feel like it can happen on other devices that are similar
i can't narrow down any specific scripts that could cause it
apparently it can happen with coroutines but i don't have many of them and have tried turning off the more expensive ones with no dice
Might need to share some more profiler info.
and none of them are running consistently enough for that to happen
it's fairly consistent 2-3 seconds
You're talking about that spike, right?
Consistently spaced spikes like that are often because of the garbage collector, which ticks around once per second or so
But you need to put your cursor on the spike and see what is happening in the hierarchy view of the profiler
This is not the spike frame though.
oh actually that's others not garbage collecter
And we need to see the hierarchy mode.
so it's the urp render stack but there are no different settings to my pc
the editor aswell but that could be cause i am fucking around with it
That's not the same as the previous screenshot though. It had 83ms in the player loop.
This looks like something with rendering..? I'm not sure why it allocates 200kb there.🤔
Maybe adding/enabling new cameras or something?🤔
there are 3 cameras but i didn't enable anything
Are you manually creating textures/rendertextures or anything like that?
yes i've got one
although there are 4 that aren't being used with cameras that are disabled, could them being in the scene at all impact performance?
well i'll see
yeah no it's still there
the render textures won't change this
also worth noting that it doesn't always happen but i'm not sure what changes for it to start happening
are you getting the colors of a texture for a postprocessing effect
kinda, i'm analysing the pixels of the texture but it's not consistent with the hitch
okay
and it happens even with the script disabled
the hitch happens, or the allocations?
what is "it"?
what is your goal? you have long frames? or do you mean those spikes of long frame times?
first, test standalone. do you see any issues in standalone?
then, try deep profiling, and identify where you spend a large amount of time in your own code.
deep profiling is accurate in the sense of relative comparisons between fast and slow within your own program
you aren't showing enough in the urp render profiler entry. you have to show where the 203.4KB comes from. it is almost certainly where you get texture pixels
which also doesn't work the way you imagine it does
@marble wasp is this helpful?
it sounds like there's a lot going on in your scene.
the hitch yeah, i'll investigate further
and there is this is relatively late in development
and something that's been happening for a while but i've not really noticed/paid attention to since it only happens on my laptop which i only use at uni
i might try building it aswell since the editorloop seems to be a pretty big contributor
can you profile a build?
okay so it's because of my recent script but that 200kb is consistent despite the hitch
it's always there cause i'm not limiting how often it happens
Yes, that's the most accurate way of profiling
okay... so these are postprocessing effects that are using GetPixels?
i mean that generates a ton of garbage
it's pretty much exactly what i thought it was, regarding the allocations
that's separate from the frame times
yeah i've just done a script that changes the material per camera
which i've been trying to optimise, it is super unperformant
but i think it's unrelated to the spikes
anyway dont' stress this is all tractable to fix
yeah something i'll deal with later
can you profile the standalone build and find what is actually taking a lot of time in your own scripts?
yeah building now
@marble wasp you should start by reading https://blog.unity.com/engine-platform/games-focus-profiling-and-performance-optimization and doing everything in it
it has a flow chart
man i wish they taught us this shit at uni lmao
Most of developer's education is self learning.
in a typical layperson unity scene, and eyeballing the tiny amount of profiler data you've shared, your scene probably has a large number of meshes and/or large numbers of transparent elements; and default shadow configuration. shadows are computed on the CPU.
in this situation, you waste a ton of CPU cycles on shadow mapping
could be my shader, although this has been happening since before i made my shader
yeah
it's hard to make a shader that is broken enough to cause this issue, but not broken enough to completely halt your game
yeah i figured that out like a month into my course
now i am a month out of graduating, sunk cost fallacy hits hard
it's also been happening since before i switched to urp
which is weird
all performance issues in all software are cause by code with time complexity
O(n^k) where k is between 1 and 2
because anything worse is unusable or never authored, and anything better doesn't cause issues. shadowmapping is O(n^k) 1<k<=2
that’s a bit misleading. It makes it sound like the time complexity is the main cause of slowdown
a lot of the time, issues are caused by the leading constant
overhead is frequently a big deal
okay so
hitch is not happening in build
lol?
it's also running way smoother
this might just be an issue with my laptop i'm overthinking
it's an editor issue
yeah. i would also check if you are spamming Debug.Logs or something, because that requires to print a whole stack trace
if you do too many of those every frame, your game will lag in editor as well
meaning you can't really say performance in the editor is representative of performance in game
you also never showed the whole profiler hierarchy
nah i've only got a few debug logs
and it also doesn't happen on my pc
like at all, not even a small hitch
so i guess i can say it's fine for now, i just can't do extensive testing on my laptop
If they object is destroyed/scene is changed does the UnnityEvent unsubscribe automatically?
which object?
If the publisher is destroyed, all the subscriptions go away
If the subscriber is destroyed, they do not go away
If my UI has:
Game.Instance.onGoldGain.AddEventListener(UpdateGoldUI)
will it RemoveEeventListener(UpdateGoldUI) when this UI element is deleted or scene changed?
what is "this UI element"?
so there will be an error if I try to Invoke the event and the subscriber doesnt exist anymore?
If Game.Instance is destroyed, all siubscriptions will also be destroyed
If whatever owns UpdateGoldUI is destroyed, the subscription will stay and you'll likely get an error when the event is invoked
That makes sense yes
Thanks, thats what I needed to know.
So I just need to unsubscribe from all events when I switch a scene for example if my Game.Instance is not deleted between scenes.
Best practice is that if you do AddListener on OnEnable, you do RemoveListener in OnDisable
I do that when I can, but some of my code makes it impossible since I need to wait for the class to be instantiated.
Unless a constructor has a priority, which it probably does.
I dont have code in front of me right now.
Can I instantiate a prefab with a constructor?
I do this:
//CharacterUIManager
private void AddCharacterCard(Character characterData)
{
CharacterCardUI characterCardInstance = Instantiate(characterCardPrefab, characterList);
characterCardInstance.Init(characterData);
}
// CharacterCardUI
private Character character;
public Init void(Character _character)
{
character = _character;
}
private void OnEnable()
{
character.onCharacterUpdate(UpdateCharacter);
}
This will throw an error as OnEnable cant access character yet.
You shouldn't use constructors with MonoBehaviours. The way you are currently doing it is fine - the initialization I mean
private Init void 🤔 something's off here...
my bad, a habit of making everything private 😄
You can move the subscription to the Init method, but you still need to unsubscribe in OnDisable.
Thats what I do currently, I tried to follow the best practices, but it wasnt possible.
I mean it should be private void Init to be syntactically correct
Making everything private by default is good
ah yeah sorry thats a typo, but I cant access it if its private since I need to call that right?
I use internal sometimes, but it seems to be useful for specific cases which dont apply to me.
Alternatively, use OnDestroy to unsubscribe as it's a closer counterpart to initialization
But it has a small issue, that is OnEnable might be useful too.
I might just do an if statement I guess?
Is there a way to check if current Character is already subscribed?
Oh yes, in this case you want it to be public or internal
Check if it's null maybe
There is AddListener or RemoveListener, is there something like HasListener?
I might be confusing it now
In this example there is only 1 listener per Event since its just to update UI, but in case I ever have more than 1, what can I do?
Not sure if null will work for this
When using events, you can remove the subscription before subscribing, to make sure there's no duplicates: cs SomeEvent -= MyEventHandler; SomeEvent += MyEventHandler;
So maybe that will work with RemoveListener/AddListener too?
I guess that I can do this:
void OnEnable()
{
if(character != null)
{
character.onCharacterUpdate.RemoveListener(UpdateCharacter);//removes listener if any
character.onCharacterUpdate.AddListener(UpdateCharacter);//adds a new one
}
}
This woud "refresh" listener
right you got it 😄
Yeah, that's what I meant. Worth a try
Thanks, that should do the trick.
bro, can someone help me with detecting joystick through script
i'm trying this code, but controllers.Length value never changed, even if i plugged out any joystick, the value never changed
IEnumerator CheckForControllers()
{
while (true)
{
string[] controllers = Input.GetJoystickNames();
if (!connected && controllers.Length > 0)
{
connected = true;
Debug.Log("Connected");
}
else if (connected && controllers.Length == 0)
{
connected = false;
Debug.Log("Disconnected");
}
yield return new WaitForSeconds(1f);
}
}
void Awake()
{
StartCoroutine(CheckForControllers());
}
From my experience with the Input class, setting up joystick input isnt always ideal, Unity does have a "new" Input System package that handles joysticks quite well, and can allow you to bind input such as a jump for example, to both a keyboard button and a joystick button - if your on a older version of Unity, you could look into something like Rewired
Input.GetJoystickNames().Length will always return the number of joystick axes you set up in the input manager, regardless of how many are actually plugged in
Yes definitely use the new input system for whatever this is
aight thanks
Hey guys! I am pretty new here.
I am thinking to start with C# as my programming language, any suggestions on where I can start?
Could ask over here;
https://discord.gg/csharp
If you want to learn C# in Unity, you can start by doing the pinned resources in the top right of #💻┃code-beginner.
If you just want to learn C#, I can't really give a suggestion.
tysm!
sounds good, ty
Hello, I'm trying to download scene before loading it with addressables. But I got this error.
Scene 'Assets/_Project/Scene/Main2Scene.unity' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
private IEnumerator DownloadAndLoad(AssetReference scene)
{
AsyncOperationHandle downloadHandle = Addressables.DownloadDependenciesAsync(scene);
_titleText.SetText("Downloading");
while (downloadHandle.Status == AsyncOperationStatus.None) {
yield return null;
string txt = $"download progress = {downloadHandle.GetDownloadStatus().Percent}";
_percentText.text = txt;
Debug.Log(txt);
}
if (downloadHandle.Status == AsyncOperationStatus.Succeeded) {
AsyncOperationHandle<SceneInstance> handle = Addressables.LoadSceneAsync(scene);
_titleText.text = "Loading";
while (handle.Status == AsyncOperationStatus.None) {
yield return null;
string txt = $"{handle.PercentComplete}";
_percentText.text = txt;
Debug.Log(txt);
_progressImage.fillAmount = handle.PercentComplete;
}
if (handle.Status == AsyncOperationStatus.Failed) {
ShowError(handle.OperationException.Message);
}
} else {
ShowError(downloadHandle.OperationException.Message);
}
}
I found solution https://forum.unity.com/threads/downloaddependencies-causing-loadsceneasync-to-fail.1495448/#post-9363890
if i have a MonoBehaviour X, with a class Y which inherits from X; and X subscribes its virtual void HandleTransition() to a static event Action delegate in its Start(), will Y's override void HandleTransition() also subscribe to it? i would assume (hope) so but im double checking. i cant test it out at the moment..
Hard to tell by the way you wrote it. The override method will be subscribed to the event but not the base one.
Yes it should 
Hey there, does anyone know a good way I could have all my Skins for my game in one place. The skins are a png that I am making a sprite with. But the problem is I have 2 scenes and the information has to be accessable in both scripts. And I would want it to be easily done in the editor. I made a class like this ```cs
[Serializable]
public class Skin
{
public int skinId;
public Texture2D skinTexture;
}
and then I am making a List of that type Skin, which is public, so that I can drag the skin pngs in there.
```cs
public List<Skin> skinList;
I am just facing the problem that I have to create this list once in each scene, which is a really bad way of handling this. And I would like to have this information in one place where it is accessible from any script in any scene. Any suggestions on how this can be achieved? And is it possible to have the skinId increase by 1 by default?
good. thx for ur answer
Make a scriptableObject with your Skin List, then you can drag that into each object that needs it while making sure you only need to create 1 list.
thank you 🙂
hello, I want to make unity application consisting of two scenes and each scene works on different monitor at the same time, does any one try this before ?
i don’t think that makes sense
Sounds more like you want two cameras and not two scenes. Camera component has a field for target display.
a scene is like a giant prefab that destroys everything you have loaded when you try to load it
can application decide which physical monitor it shows on?
ask the OS to return a list of monitors attached to the computer and choose?
https://learn.microsoft.com/en-us/windows/win32/monitor/getphysicalmonitors
looks like there are ways to do that
Anyone know why instantiate isn't actually instantiating
AssetBundle is being loaded fine I know that much
The GameObject in question is 100% called TestLevel I've double checked so many times
dont think this works in unity
seems win32 specific
Wait to add onto this my variable isn't even being assigned (testLevel)
sounds like you need to do some troubleshooting, either attach a debugger or include some debug print lines, and establish what code is actually executing & with what values
Will do give me a mo
Only reached line 1. Its saying it failed to read the AssetBundle data
And unable to open archive file
Oh yeah wait its looking at the wrong folder
Let me re-run it at the right one (it still breaks at the right directory)
I see its reaching line 1 because I have test scripts applied to the AssetBundle that only exist in that project smh
Gonna have to do it in an editor script
Okay done a bit of fiddling and the AssetBundle no longer uses outside scripts. Cant believe I made that mistake
Let's see
Why is it still only reaching line 1...
Nevermind I got it. For some reason I had to change the variable type from GameObject to UnityEngine.Object and back
anyone using the cinemachine 3.0 package, how would I successfully get cinemachine components now? with the older versions it was like this:
_cinemachinePov = firstPersonCam.GetCinemachineComponent<CinemachinePOV>();
but now with the 3.0 it returns an error
(even after changing the cinemachinepov component to its new equivalent)
the main purpose that I want to display this app in two monitors and each monitor with defferent scene
There is something called multi-screens and this is what I want help with, please if anyone tried it before, let me know
how diffcult could it b right?
try it.
Dont have two monitors but I assume it can be as simple as assigning each scene a diff camera and each camera a diff monitor output then load scenes together? worth a shot
Hi everyone. I wanted to use the toast message in my app but I couldn't find anything. After a long time I was able to find it but this message will only be in one language.I wanted this message to be in the language of the phone, what should I do?
Hello, how can I switch between HorizontalLayoutGroup and VerticalLayoutGroup at runtime?
I get current error : Can't add 'HorizontalLayoutGroup' to Sub Categories because a 'GridLayoutGroup' is already added to the game object!
I'm destroying the previous layout and addcomponent the new layout but it refuses saying the previous one is still present.
I've tried to delay the addcomponent by 1 second with same error.
I've also try to rebuild canvas after destroying and addcomponent but still the same error.
How could I make it work?
try a GridLayoutGroup
gridlayout has variables for rows and columns. You can just change rows=1 vs columns=1
gridlayout pretty bad tho
The problem was that gridlayout has fixed element size. I wanted one element to be longer
it doesn't behave with content fitter and other ui components as you expect
But only in a special case.
oooooh. yeah, that’s a problem
In the end, I changed my way of thinking and instead added an ignore layout on my different element
It's not optimal because it won't position itself automatically anymore but I'll live with it
this is hackey, but could you enable/disable the horizontal layout group, then have 1 gameobject with a horizontal layout group, then a child with vertical layout group
i forget if they can be disabled
Wouldn't work since horizontal would apply to the vertical child, not the vertical child children?
cinemachine 3.0 has the bottom values in the new InputAxisController which can be used to affect the sensitivity of the mouse - is there any way to modify these values by code? doesn't seem to be modifiable at all; hoping that I don't need to create a custom extension
oh, i think that is right
then my next suggestion is to destroy the old layout group, add a new one, and populate settings via code
it shouldn’t be too expensive
it is very strange to want the exact same thing laid out with a vertical vs horizontal layout group with no modification tho
That's what I did but got the error
Can't add 'HorizontalLayoutGroup' to Sub Categories because a 'GridLayoutGroup' is already added to the game object!
And I missspoke, I wanted to change my grid to horizontal actually
next suggestion: separate gameobject with the vertical layout group, then transfer all the children between the two objects
Because I wanted a longer width element, which I couldn't get in a grid
Yeah indeed, that would work too.
that might be the cleanest and simplest way tbh
I think so
idk if that transfer will fuck with rect transform tho
so you need to check
like how transforms try to keep their position when you set parent, right? just check that it works right
also, you probably get the error because you are calling Destroy on the component, which only queues up its destruction for later in frame
Hi everyone. I wanted to use the toast message in my app but I couldn't find anything. After a long time I was able to find it but this message will only be in one language.I wanted this message to be in the language of the phone, what should I do?
which toast?
Context: Yo! I'm watching this tutorial and I noticed something I've never seen before regarding [SerializeField].
The YouTuber has a script where it says [SerializeField, Self] and [SerializeField, Anywhere].
Question: How do I accomplish the same?
Video with timestamp: https://youtu.be/h8ZAOWY_5LA?list=PLyX8wd-3zMu36iAbTbRZzw0WVIrbHmXpp&t=396
What I've done:
I've looked at the Scripting API but there is no mention of this kind of attribute (https://docs.unity3d.com/ScriptReference/SerializeField.html).
I've tried writing something similar in my own project:
"[SerializeField, Self] private Rigidbody _rigidbody;".
But my IDE (Rider, same as YT guy) gives me an error that says: "Cannot resolve symbol 'Self'".
I've also looked into the namespaces he uses but I can't find nothing of this type of things mentioned in the GitHub repo.
Here is the link to the namespaces:
KBCore.Refs: https://github.com/KyleBanks/scene-ref-attribute/tree/main
Utilities: https://github.com/adammyhre/Unity-Utils
I found the answer while writing this 🫠.
I just downloaded the source code he has linked in the description of his video. If you inspect the same script, the 'Self' and 'Everywhere' attributes does in-fact come from the KBCore.Refs namespace 😅.
Sorry for bothering!
Toast message on Android. Like the message that appears when you exit the application by pressing the back button,(tap again to exit)
am I going insane? Why does the order of multiplication matter?
rigidbody.MovePosition(transform.position + movement * speed * Time.fixedDeltaTime);
because Vector3 * float is 3 operations
and float * float is 1 operation
thanks
they should normally be pretty close to the same final result
but reducing total multiplications makes it faster
Feels strange that it is like that but I also see why
it doesn't matter in almost any case
vector3 * float * float costs 6 multiplications total.
float * float * Vector3 costs 4 multiplications.
The difference is like 8 ticks on a processor
Isn't that something the compiler fixes?
In what way?
compiler does not know that multiplication is commutative, because you could have defined the * operator however the hell you wanted
I could make: Vector3 * float means Vector3.x = float. Then define float * Vector3 makes vector3.y = float
because I could have defined it however I wanted, compiler can’t know it’s commutative
and order of operations COULD affect the final result, so it will not rearrange algebra for you
Also what you are saying here
transform.position + movement * speed * Time.fixedDeltaTime
is
((movement * speed) * Time.fixedDeltaTime) + transform.position
Very easy optimization so might as well get used to doing it
Hi everyone. I wanted to use the toast message in my app but I couldn't find anything. After a long time I was able to find it but this message will only be in one language.I wanted this message to be in the language of the phone, what should I do?
Toast message on Android. Like the message that appears when you exit the application by pressing the back button,(tap again to exit)
I want my game to be able to be toggled between fullscreen and a resizeable widow. Everything works as expected with this code
Screen.fullScreen = !Screen.fullScreen;
and the project settings shown below, except whenever I load Scene 0 (main menu), if the game is in fullscreen mode it will automatically be changed to windowed... Other scenes load just fine, the above code is never called, and Screen.fullscreen is not referenced anywhere else in the codebase. Can anyone explain this or help me fix it?
https://docs.unity.com/ugs/manual/authentication/manual/unity-player-accounts
Looking for help with the code presented on this site. It simply does not work anymore (For example the awake function)
Hi guys, I'm having an issue with the CharacterController.Move() function, I'm using it to simulate physics on the player, code looks simple, simply like:
characterController.Move(velocity * Time.deltaTime);
But somehow it cancels out other transformations, in my case, the issue is with an enemy trying to pull me, it works just fine except for the player, who remains where it is the whole time...
What do you mean by "other transformations'?
I'm doing transform.position modifications.
If you're using CC.Move you would need to put all your movement into that call each frame. You certainly can't move via the transform when using a CC
Don't
So a character controller may only use CC.Move??
How is teleportation supposed to work in that case?
You need to disable the code temporarly that makes the player move
You then teleport him and renable it after its done
its not that complicated
Does anyone have a favorite article/tutorial on character design around decorator pattern for runtime behavior changes(like adding armor with X stat increase, or adding Y ability)?
Create a bool and use that as a condition to execute the CC.move code
And if you want to teleport the player simply set it to false
Is this restriction limited to that method not calling during the frame you applied transformations?
Or can you disable and enable it during the same frame just like that?
Okay thanks
it can be done within the same frame yes
Yeah or just disable the whole CC that works too
Any news on C# .net6+ date? I am currently making systems that I wouldn't if I could just use microsoft.extensions
They haven't announced anything yet, but it's not soon. My guess is we'll see it in the second half of 2024.
And webgpu?
Ive been able to find bug threads of people having issues with games launching with the wrong screen type but still nothing regarding changing window type on scene load... do i need to file a bug report?
how do you call the code above?
There is a listener on a UI button toggle
If the code isn't getting called then maybe there is something wrong with the button?
I mean the code gets called when i press the button... just not when the scene loads
but the game exits fullscreen when the scene loads
I never had a game change to windowed on it's own. Something most be triggering it in your project. Maybe start windowed and see if it automatically gets set to fullscreen.
it doesn't... only fullscreen to windowed
This should display the issue pretty clearly
Try an mp4 to be viewable on discord
mkv requires a download
As you can see, the only thing causing the game to leave fullscreen is loading the menu scene... I really don't understand what is going on
Does someone know how to fix prefab facing down but going towards right direction via script? I tried many methods but nothing works. This is how the code looks: var b = Instantiate(bullet, firepoint[i].position, firepoint[i].rotation) ; b.GetComponent<Rigidbody>().velocity = firepoint[i].forward * bulletSpeed;
Well if it's shooting the correct way with .forward, then your mesh isn't alligned with the rocket looking forward. So you need to either change the mesh, or add an empty gameobject as its parent, and rotate the rocket the correct way as a child.
Is this KiB per minute or second?
ah, I guess the average consumption per second will need to be calculated manaully?
Good question
Might want to ask that in the most relevant channel, see #🔎┃find-a-channel
Hello, why isn't GameObject's position assigned instantly when I do it?
I cannot get the GameObject with Physics2D.GetRayIntersectionAll on its newly assigned position
Trying to get it just after assignment on the same frame
there should be a method for this to update it instantly, I suppose?
SyncTransforms right before you use the physics query. the physics system has not updated between your position change and the query so of course it won't immediately find it because physics doesn't know it is supposed to be there yet
I see, do you have a clue whether SyncTransforms method is bad for the performance?
it's probably not great, but the alternative would be to wait until after the next physics update to perform the query
I have learned to move rigidbody.position
Physics2D.SyncTransforms goes out and syncs transforms for ALL rigidbodies in your game at the time.
moving rigidbody.position automatically shifts the colliders it is tied to instantaneously.
i forget if you have to also move the transform as well, but that is something you should be aware of.
moving transform effectively moves everything EXCEPT rigidbody/colliders, instantly
if you move rigidbody.position, all your casts/overlap/distance/etc queries will reflect that new position, as soon as that line has been executed.
I was using Physics.SyncTransforms() and wondering why it didn't work. I have a 2D project.
Now it works perfectly, thank you 😄
well, maybe it's more efficient
just make sure not to spam it. that is an expensive thing to call
SyncTransforms does work on EVERYTHING. Moving rigidbody.position moves just that one rigidbody
so they aren’t moving then
sure they aren't
I wonder if I can achieve the same behaviour with 2D Rigidbody as without it?
rigidbody is just a component to interface with unity’s physics system
yeah, but adding it may cause me some issues
rigidbody allows the physics system to: 1) solve physics with velocity/forces/etc, 2) move/query colliders accurately with physics queries, 3) generate contacts and collision callbacks
you move the rigidbody
then the collider positions match the rigidbody position
if a gameobject has a collider but no RBs, it is assumed to have a static rb
rather it behaves similarly as far as physics system is concerned
you can just give it a kinematic rigidbody, and turn off physics simulation
but then you also won’t get collision/trigger callbacks
I see, but can I add a 2D Rigidbody that doesn't change the item's behaviour at all, just makes me able to access its Rigidbody.position ?
a kinematic rigidbody
yes, but the colliders won't collide
it would change behaviour in receiving callbacks, but you could use overrides to turn it all off
that is not what you asked for
you asked for moving colliders without affecting behaviour at all.
a kinematic rigidbody will do that
No, I asked how to add a Rigidbody2D without changing my GameObject's initial behaviou at all
that includes all colliders collisions
yes, I'm not
ok. adding a kinematic rb will do that then
Ok, I'll try it out. Thank you 😄
where can i learn how to structure the scripts and the general structure of my game?
Use Unity !learn for Unity basics. Otherwise, maybe just some practice?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello, Im trying to solve a problem with cursor... I need to move with Cursor using keyboard. Im using new unity input system and Mouse.current.WarpCursorPosition()... It gives me back vector2 in console so I know input system works when i push the buttons but cursor moves only Up and Left... Any tips?
show current script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class LeverCtrl : MonoBehaviour
{
private Vector2 currentInput;
public float value = 1;
public void OnMouseMove(InputValue movementInput)
{
Debug.Log(movementInput.Get<Vector2>());
currentInput = movementInput.Get<Vector2>();
}
private void Update()
{
Mouse.current.WarpCursorPosition(currentInput * Time.deltaTime + Mouse.current.position.ReadValue());
}
}
[RequireComponent(typeof(Collider2D))]
public class DrawCollider : MonoBehaviour
{
private Collider2D colliderComponent;
void Awake()
{
colliderComponent = GetComponent<Collider2D>();
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
if(colliderComponent is BoxCollider2D box)
{
Gizmos.DrawCube(transform.position, box.size);
}
else if(colliderComponent is CircleCollider2D circle)
{
Gizmos.DrawSphere(transform.position, circle.radius);
}
}
}
is there any reason this doesnt draw the gizmo? ( i have BoxCollider2D attached )
is gizmos enabled in scene view ?
yes
are you getting console errors?
OnDrawGizmos runs in the scene too
you are probably spammed with Null ref
lol
im not getting Nullrefs
oh wait the ifstatement nvm
The Obvious™️, but just in case, the script is attached to something right
thought it was a loop for some reason xD
yessir
Then none of the if statements pass
Logging the collider type should tell you what it detected: Debug.Log(colliderComponent.GetType())
but why? it is a box collider 2D? can it not see that?
sure lemme try
do i put that on the Start()?
Yeah that's an option

Place logs in both if statements, as well as outside of them, make sure two of them are logged (the one outside and one in an if statement)
it logs twice cuz its attached to 2 gameobjectss
oh
i misread ur sentence
hold on
why the time.deltatime ?
and you sure this possible, never tried forcing a cursor pos before so I'm not 100
I'd make this easier and store the position as a variable, and add the vector input to that each frame
is this same issue?
its kinda different... actualy this is only one ive seen 😄
its working for up and left
But yeah a variable like private Vector2 mousePos; + mousePos += movementInput.ReadValue<Vector2>(); should work just fine. Then pass that vector alone to WarpCursorPosition()
No need to make it complicated and include the current mouse position (which will not be correct until the next frame as per the documentation) into the calculation
@simple egret Sorry, i got interrupted. it never seems to call the function, even before the if-statement
Hmm, docs say
This function does not get called if the component is collapsed in the Inspector.
Make sure the script is expanded in the Inspector
its not collapsed
It took me ages to understand it as Im not so good at coding but it finally works! Thanks so much! Cant believe it was so basic...
How can i do get value negative in the input with the new input system???
still dont know what caused this... i had to go back to a previous commit and rebuild
What do you mean? What value are you referring to?
Hi, I'm building a wall placement and connecting system, but I'm having trouble placing a wall perpendicular. When I place the wall, the wall does connect perpendicular, but not always on the correct side of wall 2. For example, I might try to connect it with the bottom right side of wall 2 perpendicular, but it gets placed on the top left side of wall 2 perpendicular.
I can get a short video of what it looks like if it helps or I can share code
share !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
ohh thought you were using rays
are the debugs correct ?
What I did seemed easier
The logs? They are printing. Sometimes one gets printer, sometimes the easier.
Would raycast be better?
Any solid examples anywhere I can copy?
I wouldn't say better, there can be many approaches..its thats how I did it when I did something similar so just cheated by getting the face of the normal easily
I would also not write Debug.Log("cross product y less than 0");
and maybe Debug.log the actual angle , making sure the numbers are what you expect them to be
Ah, very good point
Someone else recommended creating game object (snap points) from one of these:
I only created a snap point on the top of wall and bottom of the wall on the edge.
With these images, they even have more snap points than that
The top may have 3 snap points, or in the right image, 4 snap points
its pretty good approach as well
hi what would be the best way to reference a specific parent of a hit collider consistently. imagine i have an enemy gameobject with two children that have colliders (e.g. a headshot collider and a bodyshot collider). Up until now ive been using transform.root.gameobject to identify the highest parent when hitting one of the colliders, (e.g. the enemy and their script), but what if i want to put the enemy in a prefab for a level? That would become the highest parent and would ruin it entirely. I also can't just do the parent of the collider (or any measured number away from where the collider is) since some colliders are lower down in the hierarchy, attached to specific parts of the enemy's model. So whats the best way to make this work? Any help would be appreciated.
Add a rigidbody to the root (can be kinematic) and then use collider.rigidbody.GetComponent<Whatever>()
That's the easiest way using built-in stuff
If you have an RB just do that
GetComponentInParent with some component on the desired object
e.g. for an enemy
hitObject.GetComponentInParent<Enemy>()
which has the added bonus that you should realistically only interact with the Enemy script anyway
That's also an option that's fine, quick linear search up the tree. It's fine so long as you don't have a really deep hierarchy below objects that do not have that root Enemy component
if my root is a prefab level for instance, how would it differentiate multiple enemies within it when i use getcomponent?
oh, I was imagining for hitting enemies too
I wouldn't put a rigidbody on a level lol
For both of our examples it will find the nearest such component in the tree.
So you want to find a level when hitting any collider? Just do GetComponentInParent
Beacuse that's static geometry
You can't be putting a rigidbody on it
no that was just an example. my issue isn't with finding the component, its with consistently gettingcomponent at different positions in a tree i guess
Well then why don't you read the answers you've already been given?
lol
I don't understand what your'e asking for now
sorry still googling how getcomponentinparent works. Wasn't meaning to sound rude just trying to clear things up, all help is appreciated
it finds the nearest such component in the tree, traversing upwards toward the root of the tree
it's almost definitely what you want
oh so do a loop using that until it finds one? gotcha thanks a ton. is this bad practice though? I feel like it may be expensive?
you don't need to do any loops
it does the loop internally
oh its part of the function
and it's not expensive unless your hierarchy is hundreds or thousands of elements deep
oh ok thats easy then, thank you
yea that shouldn't be an issue
Object getting stuck on walls even tho its radius is large and the wall is obviously a collider. Never had this issue before.
how is said object moving?
shot in the dark but perhaps ... [ExecuteAlways]
Im using Granbergs asset. The object has a seeker component. Just setting the AIPath destination to that point
Never had an issue with this before but its been like a year outside of Unity
not familiar with it - but likely it's moving your object via the Transform directly or something of that nature
certainly sounds like a problem with the asset or how you have configured it.
Yea messing with some things seems towork
Are you using any path modifiers?
It's the A* Pathfinding Project, in case that is more familiar
https://assetstore.unity.com/packages/tools/behavior-ai/a-pathfinding-project-pro-87744
(There is a free version too)
How can I achieve a text effect?
Is there a built in way to make the text larger/smaller(like its "breathing") + change its color?
Or perhaps something from asset store that can do that?
you can animate the text color(s) with text mesh pro and change the size using lerp and/or a coroutine, or with a tween engine. there is also the text animator asset . . .
yes, this asset is awesome. checkout their videos . . .
Is there a way to tell the crossfade has finished?
Added it to my list, atm I just need a simple color fade
But I want it to change between 2 colors constantly.
don't think so. you can check the current text color to determine if it's finished . . .
Yep doing that now
Cant seem to figure out how to get current color
It seems like CrossFade does something else, it doesnt actually change the text color
I have to use CanvasRenderer:
GetComponent<CanvasRenderer>().GetColor()
just use lerp or/and dotween
there is also this neat example in unity for a simple one
https://docs.unity3d.com/ScriptReference/Color.Lerp.html
Mathf.PingPong helps with going back n forth
But thats what I need, thanks xD
hi friends, I want some help about image selection form local files on web platform, how can i select single image form local files and load into image
!ban @dull tulip bypass this ban
albiei was banned.
(note for future: sending CoD ban bypass exe virus)
Real.
how would I go about extracting an animation clip from an fbx in script?
why you want to do it on script?
My combat system uses scriptable objects that have override controllers with an animation for each attack in a combo. Since there are a ton of different attack animations I wanted to have most of the workload automated. At the moment I have a one click script that creates the SO, AOC and stores them in a folder. I was then trying to get it to duplicate the animation clip so I could go in and manually add animation events manually, but the source clip is an fbx and the animation will still be read only even if I duplicate it
TLDR I want to take a couple clicks out of my workload
you mean you get trouble with add event to anim clip readonly in fbx file?
Yeah
just for sure, you want to auto add event by code?
Not the events, just getting a clip that isn’t read only. Since each animation is different I’ll have to manually add events at specific poi’s
1, if you want to add animation to a anim clip readonly on fbx file, at tag Animation, roll down you will have this
hey sorry i was asleep. i just tried it, it didnt work. Which is weird cuz the gizmos draww during play mode
2, if you want a editable anim clip, select the anim inside and click ctrl + D
you will have it duplicate editable
hmm.. do debug logs show OnDrawGizmo() is even being called in not-play mode?
I’ll see if 1 works for me, I know in the past unity has given me a hard time adding events that way but I’ll give it a go. #2 tho was what I was attempting to automate, but I’ll try 1 before I ask about that further
Hi all
I want to be able to make a 2D sword follow the player
But not always be stuck to his hand, like just float around him
How would I go about coding this mechanic in?
It's such a difficult topic
Determine the point on your hand where the sword should be, and then lerp the sword to that position using the same angle/pitch/roll as the point I guess
I don't understand
But I want it to wander around
And constantly revolve at random positions around the player
Around the player?
Then determine the player's position and determine random spots around the player to move towards, and do that
Maybe with an angle that constantly increments a random value on both axis
And just lerp?
And sine/cosine
Sure
I'll give it a go
Thank you
Combining those should give you a decent circle to work with
In all seriousness, you could even ask ChatGPT how it would do this, and it would probably also suggest sine
Just make the code yourself
Ik how to use sin
I was just using it
But the issue was making sure it didn't jerk around
I didn't know I could use lerp for that
Yeah then just lerp it
Thanks
Lerp will account for the remaining distance so it might speed up/slow down
Yeah
I'm working on a procedural level generation with tilemaps. Everything is made programmatically. I'm having a lot of tile combinations I would like to "prefab" (items made with several tiles, ie doors, walls, etc.)
What is the best way to achieve it? Currently I'm making prefab of a tilemap for every tile combination I want. At runtime, I'm getting the right prefab, clone it, move it and add it to a Grid. At the end, I have an individual tilemap for each element.
Hello guys I don't really know if I should be asking how to fix these two errors here or in some where else
I've done as much research as I can but Nothings really working
In fact spent over 12hrs in the last 2 days trying to fix it I went into the script and As far as I can see everything seems to be in place
go ahead
what are the errors?
these two errors Code is error CS1061:
It tells me this
'VRCAvatarParameterDriver' does not contain a definition for 'ApplySettings' and no accessible extension method 'ApplySettings' accepting a first argument of type 'VRCAvatarParameterDriver' could be found
not your code?
can you take a screenshot?
no Its a paid for model that has scripts in it I've tried to get in touch with them but no luck
Do you need a photo of the script or error code?
the photo one
i have googled the script looks like it is vr chat
I am a little confused by what you mean?
somethings related to vr chat but i am not sure
havent tried it before
This is the start of the script I dont know much about scripts in general This was just suppose to be a premade model I could work on
meant to reply to you sorry
If you have commisioned a VRChat avatar then you should ask in the VRChat server about uploading it @teal stirrup
not commissioned from vchat
Then you don't need that script presumably? Can't you just delete it?
No, VR Chat have their own discord server. We can't answer about it here
Wish I could and tried but the script is huge and makes it where I can use many parts of the model
Buts its made from a unity Script?
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
I'll check it out ty for your time
actually, if the scripts in asset are broken you should contact the asset's creator, dont try to fix it yourself unless you know what is going on, or you are the creator.....
I've contact the creator many times but have gotten no response
oh i see.... he may busy/miss your request/ irresponsible...
Ive tried as well as my friends for almost 4 months now ;w;
we have tried to be patient but were starting to get upset since we've made over enough reports claiming the issue with no response as well as 2 others
I'm using LineRenderer to generate a connection between some source and target. Sadly it looks glitchy on some angles. Can you recommend an alternative solution?
is it a straight line?
It's a curved one. It resembles a trajectory of an object thrown in the air and being slowly pulled down with gravity.
then a Spline is probably your only other option
Thanks, I will check it out.
I recently learned that Unity Web Requests aren't supported on Linux, I was using them to load local files on the users PC. Are there any alternative methods to do so that support both Windows & Linux?
Why would you use web requests to load local files in the first place
It was the only way I could figure out how to load png files from a folder to then be displayed in Unity. If you know of another solution feel free to tell me
Oh interesting, I don't really understand how to actually use this yet but hopefully a quick google search will tell me what I need to know
Google for how to read files in C#. There's nothing special about it in Unity
unless they're files bundled with the game
Well they're in the same folder as the rest of the game, but I manually add it after the build is finished
why?
Without getting into a lot of detail, basically I'm making a tool which takes a bunch of sprites & allows the user to combine them into one sprite and save it back as a png. I wanted the sprites to be editable by the user in case they wanted to change/add/remove any, which is why I made it a seperate folder that gets loaded at runtime
Ok, that makes sense. That can be automated too fyi
Isn't using unity webrequest pretty common for local files with android builds
Haven't touched android builds for a while but I remember scratching my head over it
Idk about android builds specically but everything I see about accessing local files in Unity says to use web requests
how so?
Are you asking how to do it?
Ya, how are you saying it can be automated?
You can make a script that copies the files after the build. https://docs.unity3d.com/Manual/BuildPlayerPipeline.html
Oh you were talking about copying the folder into the build automatically, I was confused lol. That does seem useful tho. Thanks
What is the correct way to refactor a scriptable object without losing references? I want to change the name of a scriptable object type in my project but whenever I do my normal refactor in Visual Studio, all scriptables created from that script lose reference.
Change the name in Unity first
Then do the VS refactor
All the matters is that Unity knows that the new script asset is the same thing as the old script asset
If you rename in Unity, it updates the corresponding .meta file
critically, the GUID in that file doesn't change
If you rename something outside of Unity and the .meta file isn't also renamed, it will think you deleted a script asset and then made a new script asset
the new .meta file will have a different GUID, and now all of your references are broken
The script name should be the same as the class name. Currently my Visual Studio automatically changes the filename when I change the class name, but this is a rather new feature. If your script name is the same as the class name, but you still have some issues with detecting the referred object, you can try recompiling code or reimporting asset. Keep in mind that all asset references are made with GUID which is stored in .meta file. Unity automatically changes the .meta file name accordingly whenever you change the asset name, but it doesn't work if you change names outside of Unity, e.g. via Windows Explorer.
If the class name is wrong, it won't work correctly until you fix it -- but you won't lose the references
Ahhh this was the key. I'm used to being able to refactor Monobehaviours directly in VS and it changes file names automatically *and * maintains reference. Wonder why SO works different. Either way thank you!
@heady iris @hard estuary Yeah I had the class name and file name matching correctly but it seems like if you don't change the file name in Unity first it won't work with scriptables. Which is unintuitive because it does work with monos.
Unity needs to be involved so it knows to update the name of the meta file too, keeping the asset guid the same
Otherwise unity thinks the old script was simply deleted and a new one created, so you end up with a new meta file with a new GUID
For me it worked with ScriptableObjects too. Perhaps it's just my version of IDE and/or Unity.
Right, makes sense since there are additional files to maintain. Anyways thanks again you saved me from a huge headache.
There is no difference.
SO assets and component instances both use the GUID of the script asset to identify it
Is it possible to override the normalizedValue property in Slider.cs?
I'm running into an issue where I'm creating a shop system, and am using a slider for the player to specify how many items they want to sell. Now it works fine if there are multiple items e.g. 2 or more.
When there is one singular item, I want to set the minvalue and maxvalue of the slider to 1 (as max value is based on how many items are available to sell etc.).
Unfortunately though in the Slider.cs they are doing a check to see if minValue and maxValue are approximately the same, and if so, return 0. Therefore when selling a singular item it's always returning 0.
Any suggestions would be helpful 🙂
Couldn't you just unormalize it by multiplying it out again -> compute then return as the expect value
Add a special case in your code to check for 1 as well
Oh so you mean if it's going to be 1 then we just use the value 1 rather than the slider?
Jesus christ... I've spent like 3 hours trying to figure it out today and all it took was that... smh. I need sleep! Thank you!!
Does anyone know any good articles or videos that show various good uses for arrays and the best ways to use them in your scripts instead of just showing how to set up an array.
Ooo thanks I'll check that out after work!
what is "good use" btw.....
it is nothing more than a contiguous memory block....
Like practical ways you can use arrays along with loops in games, that are useful for certain mechanics of a game.
I'm not sure if I'm wording this right tbh 😂
arrays go well with loops since thats one way you'd interact with all them at once
Yeah
nothing really concept heavy about how to use them. Pick the appropriate one for job.
Eg sometimes a while loop makes more sense than for
or maybe foreach over for. etc
just be careful with while loops as they're easy to fuck up and create endless loops 🫠
Yeah that's true, that Microsoft page you sent is quite useful tbh thanks for that
Lmao yeah that's fair
yeah microsoft really stepped up their docs/learning. It used to be ehh not so friendly lol
or recursive way to visit an array, though you wont see anyone do that in c#, just for fun
void dfs(int[] arr,int idx){
if(idx>=arr.length)return;
work here
dfs(arr,idx+1);
other works here
}
I'm aware alot of programming is independent and personal research and that it works better if you spend time experimenting on your own haha. so I'll probably use those docs you sent and try out stuff see what works and what doesn't. I've definitely seen improvement in my programming the last few weeks when I decided to rely less on tutorials and just go on my own and experiment I've been able to figure out some more stuff independently and use documentation to help
Oh damn that's cool haha
awesome! what really helpedme drive some concepts home is also working doing small apps in Console
Absolutely that's what I've found myself doing recently that has helped alot!
I'm going to definitely have a read through the Microsoft documents after work, they seem really useful
are null exceptions slow?
or are they the same as if i simply returned from a method (performance wise)?
throw any exception slowing down your program
ok
id be more worried that its breaking the code from executing properly than it being "slow"
u shouldn't ignore any NRE
try pattern is quite good, do the checking and performing the action at once, though i wont suggest just simply returning a bool back, instead returns some status eg
struct SomeThing{
const int Success=0,FailReason1=1,FailReason2=2....;
readonly int errorCode;
public static implicit operator bool(Something s){
return s.errorCode==Success;
}
}
```annoying, but more infos
Hello, so I want to create code where I have a GameManager script, which checks between the collision of two seperate objects (preferably with tags). I have tried to use an if function to do it seperately, but it doesnt seem to work? What is the easiest way to do this? Do I create GameObject variables or?
Thank you!
Also it is the collision between the player, and an object from a list of three possible objects
if two objects collide, their oncollisionXX will both being fired.
then they need to inform the GameManager (probably a singleton) they are colliding and tell the GameManager who they are.
is there a simple place to get some basic icons to give monobehaviours to make them more distinctive? I just have a ton of monobehaviours that have the standard C# paper icon thing
I think I know how to assign icons, but not a good resource to just grab a bunch of basic ones, because I don't want to waste time drawing, or searching for icons individually to download
searching is your best bet (quickest route). it's not wasteful if you need it . . .
Noun Project has the most diverse collection of free icons and stock photos. Download SVG and PNG. Over 5 million art-quality icons and free photos.
I also have this one
https://www.svgrepo.com/
there is also
https://www.flaticon.com/
ty guys
I found this site to also be good: https://icons8.com/icons
ty guys. This is much better now:
Hey guys, are there any good Built-In solutions for real-time decals? I can't seem to find any.
The closest example I found was this shader https://www.ronja-tutorials.com/post/054-unlit-dynamic-decals/
The only problem is, it's unlit only, and I can't seem to figure out how to exclude certain surfaces/models from being projected on.
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 has t...
I have a serializable class that has player position/animation data, to send over to another player. One of the fields there is a Quaternion, it is serialized, sent over but the rotation doesnt seem to set correctly, it's just weird
So I'm trying to randomize colors, how do I send the list values to the ballRenderer.color = someColor?
Why would you make a list of strings instead of Colors?
Oh, let me fix that
Make a list of Color and just select one at random from the list
Assign it directly to the renderer
Done
How do I make a list of colors?
this is still list of string
Write List<Color> of course
btw you know that goal is colliding with ball and why you want the goal finds another ball gameobject in your scene
Hey guys, I need a pathfinding algorithm for my Unity project. Normally navmesh finds the shortest path but I need a path with straight edges. It will only involve 90 degree rotation. Do you have any suggestions?
This is a valid path, for example:
Just a suggestion, that i think you should know.
using GameObject.Find and getComponent is quite ineffective, especially if it is done very often, and it can cause some problems
use singletons. in you GameManager script, create something like this :
public static GameManager instance;
public void Awake(){
instance = this;
}
now instead of GameObject.Find("GameManager").GetComponent...
you can do GameManager.instance.Player1Scored().
singletons are used only for scripts that are created once and used all the time, so GameManager in your case works perfectly for this
good advice ^
i would suggest to write it yourself. A way to do it that pops in my mind is do some math 🙂 and find the interception point from start to end. Check if there are any objects in one of the straight lines, if so move it to the side so it goes around the object, and then connect the moved line to the start/end point. Repeat this a lot
this is just a rough idea of how i would do it, but i imagine it requires more work than this
This image wouldn't be the shortest path, as it backtracks. You'd just go between the obstacles. Are you sure you want shortest path?
Anyway standard Djikstra or A* algorithms will work fine, with a rectangular grid of coordinates and a neighbor function that only returns the 4 cardinal directions.
Actually I had a very similar idea that uses Linked Lists and recursively calculates the path 😄 I just wondered if there are some ready to use techniques
in his case that would result in a zigzag path. if he needs the shortest distance, that is the best way to do it, but if he wants it clean with as few turns as possible, i doubt a* or djikstra would work
Yes, it is definitely not the shortest one. I just want a cool path that only involves 90 degrees of rotations.
Recursively calculates the path is a big "draw the rest of the owl". There are graph algorithms you should look at, like the ones mentioned above.
Not true - there's nothing about either of those algorithms that requires a zigzag
especially considering one with many turns will be the same cost as one with only two turns
you can tweak the heuristics of either to minimize the number of turns
Well you could add a huge cost to turns
if you don't want shortest path that's a whole separate world
so it tries to avoid it as much as possible
or just a slightly higher cost, but yes
exactly
Then, I will try to implement on my own and I'll share the results. Thank you guys 😀
extra cost of +1 in heuristic should be enough, force the min heap pop all Adjacency cells
T T
C<--------go right < go up until C<--now go right >= go up
S S
So how do I select a color at random?
private List<Color> colors = new List<Color>()
{
Color.black, Color.blue, Color.green, Color.red, Color.white
};
ballRenderer.color = colors.;
ballRenderer.color = colors [Random.Range (0, colors.Count)];
Oh awesome thank you
Weird it randomizes to a clear color making it impossible to see on a black background
the first choice is black
Ohhhh lol
Thank you haha
Hmm the physics of my ball are off... after enough plays it will slow down. Any thoughts?
Installed Netcode for GameObjects. This is less about networking more about why is it not showing up in VS? I tried regenerating csproj crap and it still doesn't work
There's no namespace no nothing in VS
Actually issue on my end for some reason VS wasn't suggesting Unity.NetCode as a namespace and would rather tell me to change it
Gravity is set to 0, settings seem correct
If the ball hits the paddle at the right angle it will cause the ball to slow down... how do I prevent that?
Oh interesting according to this post
There is actually a precision issue where it's impossible for an object using built-in physics to never lose any velocity when bouncing off things (or gain velocity with high enough bounciness settings). You can get it fairly close, but eventually it will drift. So you can either do your own simple physics, or check the velocity's magnitude occasionally and adjust it as necessary.
full Unity physics can be a can of worms when you just want some simple but crisp arcadey physics for sure
hi i have an issue with my character controller, it looks good like you see
but there is an issue
when i am moving my cam the gun is transforming weirdly
weirdly?
it's likely due to the positioning of the gun
probably non uniform parent
whats gun parented to ?
the parent of the gun is the camera
The weirdest thing, is that I made a crouch system that make less heigh the character, but the issue is not here when I crouch.
ohh maybe you scaled the player transform? idk its hard to tell from ss alone
I would assume scaling, or the fov is changing. Not really much to say without seeing the setup or code
yea when the player transform is at 1 y there is no issue
Non uniform scaling results in weird things
yeah its probably rotation skewing due to nonuniform
how can i do?
to uniform it
without changing everything
dont scale the main gameobject
just scale the collider
main parent should only be a container not an actual mesh
the main parent is an empty mesh with character controller
alr well dont scale transforms lol
well you can but non uniform will cause issues in children/rotations
what is an uniform thing
👀
if i set it to 2
it works?
pretty sure I scale almost every transform highest parent lol
all three numbers are the same
although ig mijne are uniform
yes
do you not scale like that specifically because of meshes?
aka Im fine to keep doing whatever since Im 2d?
some just use the scale tool and elongate player like that but then causes scale being off
its best to have meshes as children
unable to affect anything important
how do you get the "titles" on here above the serializefields?
ex)SoundFx
(stolen img from @rigid island asset store page :D)
ty anyway
really helps me
those are [Header]atribute
i wish a good day to everyone 🙂
lmao I thought that looked familiar
hmm something isn't working right
I need some advise on best practices to follow for readability and ease of use.
I have an Editor Script with some important functions and helper functions. I am planning to move the helper functions to another class and have the main class inherit the helper class.
But I also have to pass some arrays by reference to all the helper functions. So I am not sure what is the best way to implement this.
- Pass all arrays by reference- I have to pass around 7 arrays and 4 variables to each function. (I don't want to do this)
- I could pass the arrays by reference to a new function which assigns these to global variables in the parent so I have to initialize it once and then don't worry about it.
- I could use partial class instead of inheritance and keep helper functions inside the partial class. (This looks simple to do but I am not sure whether this is the best option)
Or is there a better solution as this feels a bit weird to me.
public class EnemyAttackSOBase : ScriptableObject
{
[Header("General")]
protected EnemyCharacter enemy;
protected Transform transform;
protected GameObject gameObject;
protected WeaponAttack weaponAttack;
[Header("Projectile")]
[SerializeField] protected BulletTypes bulletType;
[SerializeField] protected Rigidbody2D FireballPrefab;
[SerializeField] protected float fireballSpeed = 10f;
[SerializeField] protected EquipmentType equipmentType;
[SerializeField] protected MyWeaponType weaponType;
[SerializeField] protected AttackType attackType;
[SerializeField] protected bool findPlayerThroughGround = false;
[SerializeField] protected int numAttacks = 1;
[SerializeField] protected int numBounces = 0;
[SerializeField] protected float multishotCooldown = 0.35f;
protected int shotsFired = 0;
[SerializeField] protected float _timeBetweenShots = 2f;
protected float _timeTillExit = 3f;
protected float _exitTimer;
[SerializeField] protected float _movementSpeed;
protected bool pauseAttack;
don't think protected fields would show
so you need it to be above something that is serialized
ah ok gotcha
@rigid island can you advise me
Idk depends on your project and specific use case. Sounds like I would just use static class
not sure why it doesn't like the header here
[Header("Fighter Setup")]
[field: SerializeField] public bool isFacingRight { get; protected set; } = true;
public bool isCharacter = true;
I'm gessing some shenanigans what that being a property
very annoying
much like the SerializeField attribute, you need to target the backing field for the Header attribute
interesting...why do I need that here but not in other places like the above screenshot(a couple up)
because it's an attribute that can be attached to a field. you're attempting to attach it to a property here. it works just like SerializeField, target the backing field or attach it to a field
Even though do like serializing the backing field, there's just more clarity with spliting it up, and easier to rename the serialized variables if you need to later on.
i use a lot of automatic properties with backing field. it’s just really convenient, and it is easy to add in later if needed
you just lose the currently serialized values when you migrate later
Is there a transform.TransformDirection() equivalent for Vector3?
I have two vectors. I want to modify one vector according to another vector's direction. Any idea how can I achieve this?
Pwetty pwease :)))
Not totally sure I completely understand what you mean but perhaps:
Quaternion diff = Quaternion.FromToRotation(Vector3.forward, anotherVector);
Vector3 result = diff * oneVector;```
I am looking for a way to make sure that, as long as a character controlled by the player is moving while grounded, the direction in which it moves is always parralel to the surface it is walking on.
Artistic representation attached.
use Vector3.ProjectOnPlane and project the player's velocity on a plane with the ground's normal
My thought process:
- I take the normal of the surface my character is standing on.
- I calculate the Cross Vector between the normal and characterTransform.right and store it inside a Vector3 instance called "direction".
- I calculate the Dot Product between the Cross Vector and characterTransform.forward to see if the two are oriented in the same general direction and in case they are not, I invert the Cross Vector(direction = -direction).
No the only problem is:
When I take input from the player, I store it inside a Vector3 called "move"(Vector3(InputX, 0, InputZ)) and I use move = characterTransform.TransformDirection(move) in order to allign the "move" Vector with the direction the character is facing.
In order to make sure the character's movement direction is always parallel to the surface it is moving on, I also need to modify the "move" vector according to the "direction" vector mentioned in the thought process. That's where I'm stuck.
Thank you, @somber nacelle! I looked up the ProjectOnPlane() method only after I finished writing my previous comment and it's exactly what I need. Kudos, man!
Anyone know why testCubeItem is null?
Or well
In Awake when doing all the stuff it isn't null
It finds TestCubeItem
But in Update its null (this is after switching scenes)
@rigid island Do you think I should go with the first image or the second?
maybe First should be enough points
well you're catching exceptions there. What is it logging?
That was testing previously as I had the wrong assetbundle name by one letter lol
In awake there's no exceptions it assigns testCubeItem fine but in Update its null somehow
I'll try constantly logging to see when exactly it turns null
Excuse me what
Its never null
Why is it null when instantiating then
what makes you think it's null
When I instantiate it gives a NullRef
I don't understand why it would be null though. I'll try spawning it at the player instead
Well do you have a camera in the scene with the MainCamera tag or not
Ohh it has to have a MainCamera tag?
yes
Okay fair enough I thought it was just the first active camera
That makes sense now
I'm not sure what happens if you play an animator state you're already in
i'm pretty sure that's used for previewing animations
See Also: StartRecording, StopRecording, recorderStartTime, recorderStopTime, StartPlayback, , playbackTime.
Perhaps it will work if you specify the normalized time
see the example on https://docs.unity3d.com/ScriptReference/Animator.Play.html
// play Bounce but start at a quarter of the way though
anim.Play("Base Layer.Bounce", 0, 0.25f);
Perhaps the default behavior is to not try to change the time if you're already in that state
(you would use 0, not 0.25, since you want to play from the start)
Alternatively, you may just want to have all of your states transition back to the idle state
you wouldn't do any other logic in the animator controller
you could actually just use Any State to go back to idle
hello can you help me fix this error Assets\codes\PlayerManager.cs(17,22): error CS1061: 'InputManager' does not contain a definition for 'HandleAllInputs' and no accessible extension method 'HandleAllInputs' accepting a first argument of type 'InputManager' could be found (are you missing a using directive or an assembly reference?)
did you get this script from somewhere? Sounds like you need a HandleAllInputs function that takes a type of InputManager
did you name a class InputManager
Is it possible to make the GIU class draw to a rendertexture instead of the screen? That way I can use it to draw a texture onto another with proper filtering if I need to scale the texture I'm drawing
And if I can render the result to a render texture, then I can save that to disk
I'm asking because I don't think Texture2D.SetPixels() will do scaling if you pass a color array that doesn't have enough or has too many pixels to fill the rectangular region
I think you can do this if you set the active render texture to whatever render texture you want to use the GUI functions on. https://docs.unity3d.com/ScriptReference/RenderTexture-active.html
that being said I think there's better ways to do what you're talking about. Why not blit the render texture with a shader if you just want to draw a texture to a render texture? Or am I missing something?
what does Assets\codes\PlayerManager.cs(17,22) look like?
You should not name Classes the same names as Unity Classes
what do u mean
I think unity already has a class named InputManager
its in a separate namespace so not sure its an issue in this case
anyway you're accessing something in input manager that doesn't match signature or doesn't exist
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
dont screenshot code
I'm currently making an AR app where user has the possibility to upload images. I would like to add a function to save the images, and I've got 2 possibilities:
- Encoding the image to bytes and decoding it back to PNG/JPG when loaded.
- Simply saving the file paths.
What would be the best approach?
Just saving the file paths is lightweight, but if the file paths change, the images get lost. The chances of this happening are low, but not zero. The user does not pick the images from the gallery, but rather from the literal file explorer, so there is a chance things may move.
Converting the image to bytes might be more reliable but takes up more space. But then, how much more space would this approach take? The maximum number of images will be around 20 to 30
If the program requires the images to be updated as soon as they're modified externally (in Paint for example), then only store paths.
A bit like how Unity does it, when you focus it, it checks if changes were made in the Assets folder, and triggers a reimport
There's the FileSystemWatcher class available that can be used to monitor changes made to a specific directory. It'll raise events when files get created, moved, deleted
Passing the relevant paths as arguments of course
is the error not underlined in code editor ?
and did you save/
okay
this is acctualy funny
cuz i didnt
xD
its working
thank you so much bro
btw you should configure your code editor
this way you know in realtime if the error is there or not (above many other good features like code suggestions)
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
@sleek chasm
all good! this part is important
saves soo much time and headaches later. You only need it once
goodluck 🙂
Thanks dude cya
Okay, I think I'll save the filepaths for now, that's way easier. I'll keep the other approach in mind, in case problems arise. The thing with the other approach is that when encoding the images, loading time might become an issue. Imagine decoding 20 images from bytes to png on a mobile device. Might take a 1-2 seconds.
FileSystemWatcher may not work on mobile, you might have to track changes yourself if that's a requirement
okay, thanks for the info!
I found a utility class that can do the annoying work for me
now I'm ust having trouble with this
private Texture2D GetTextureFromBitstream(byte[]? bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key)
{
if (bitstream == null || bitstream.Length == 0)
{
var solidTexture = new Texture2D(1, 1);
solidTexture.SetPixelData(new[] { backgroundColorForInvalid }, 0, 0);
return solidTexture;
}
var imageTexture = new Texture2D(1, 1);
imageTexture.LoadImage(bitstream);
NativeArray<UnityEngine.Color> colorData = imageTexture.GetPixelData<UnityEngine.Color>(0);
for (var i = 0; i < colorData.Length; i++)
{
if (colorData[i] == key)
colorData[i] = default;
}
imageTexture.SetPixelData(colorData, 0, 0);
return imageTexture;
}
I have to do some processing on the image as I load it in, don't question the processing I need to do - I know it's cursed
The problem is when I use SetPixelData
despite me setting it on the same texture I got the pixel data from, uhhhh
it complains the texture is larger than what the source pixel data can supply
or, correction, other way 'round
ArgumentException: Texture2D.SetPixelData: size of data to be filled was larger than the size of data available in the source array. (Texture '')
UnityEngine.Texture2D.SetPixelData[T] (Unity.Collections.NativeArray`1[T] data, System.Int32 mipLevel, System.Int32 sourceDataStartIndex) (at <f712b1dc50b4468388b9c5f95d0d0eaf>:0)
UI.Themes.Importers.ShiftOS2017Importer.GetTextureFromBitstream (System.Byte[] bitstream, UnityEngine.Color backgroundColorForInvalid, UnityEngine.Color key) (at Assets/Scripts/UI/Themes/Importers/IThemeImporter.cs:124)
UI.Themes.Importers.ShiftOS2017Importer.CreateWindowTextureFromShiftOS (UI.Themes.Importers.ShiftOS2017Importer+SkinData skinData) (at Assets/Scripts/UI/Themes/Importers/IThemeImporter.cs:83)
UI.Themes.Importers.ShiftOS2017Importer.Import (UI.Theming.OperatingSystemTheme+ThemeEditor themeEditor) (at Assets/Scripts/UI/Themes/Importers/IThemeImporter.cs:63)
I was messing with this kind of stuff a while ago but my knowledge is a bit rusty. However, especially since this is just a one pixel texture, why use GetPixelData and SetPixelData? Why not just GetPixel and SetPixel? The data methods are more optimized but I can't imagine it matters that much for one pixel. Either way, the size of what you're getting for GetPixelData might not match the size of what you're setting, as weird as that sounds. I'd debug log the size of both to be sure.
Because it's not a 1 pixel texture
Ignore that
anyone have an idea why prefab instances would persist after exiting playmode? re-entering playmode doesnt clear them either
The texture gets created as a 1x1 texture because those params are required
LoadImage will immediately resize it though
I use it all the time
Oh, I see
When you make a NativeArray of colors, is that converting the data type? Your input image data stream might be in a different format?
Input image data stream is just a byte[] representing...well....idk
could be a bitmap
a PNG
a jpeg
that's not for me to care about
yeah I think that's the problem. When you convert it to a nativearray of colors, you're turning it from a potentially compressed format to one that isn't, and the new uncompressed format is bigger than the compressed format
Soooo what you're saying is it'll work better if I create two textures, and destroy the one I got the array from after I do the processing
if a monobehaviour gets disabled in the middle of a fixedupdate loop, but it hasn't had its fixedupdate evaluated yet, does its fixedupdate get skipped when it comes up?
You might want to try that, although that could be unoptimal. Still, would probably be better to get something that works first then optimize it.
FixedUpdate will finish running even if it gets disabled mid fixed update, but shouldn't run the next fixed frame. You can just "return" if you want to cancel FixedUpdate early though.
didn't work
How so? Same error?
Yeah
I would assume you are using async somehow to spawn objects or some weird editor code instead of instantiating normally. This shouldnt happen, unless prefab instance means something else
Debugger just told me everything I needed to know
Basically
LoadImage is in fact resizing the texture
but for whatever reason
GetPixelData is returning me native array of length 1
so the array is smaller than the texture, I read the error wrong
bug with GetPixelData?
I'm trying to figure out how to make my game more pause-proof, tbh
solution: don't allow pausing /trolling
setting timescale to 0 lowkey works for most things
trying to investigate the GetPixelData thing because I ran into this problem before and its interesting
What exactly do you mean by "pause proof"? What are you trying to prevent happen?
as in, resilient to being paused and unpaused?
so that it doesn't behave differently than if you hadn't paused at all
argh not this
Graphics.CopyTexture called with mismatching mip counts (src 1 dst 11)
UnityEngine.Graphics:CopyTexture (UnityEngine.Texture,UnityEngine.Texture)
UI.Themes.Importers.ShiftOS2017Importer:CreateWindowTextureFromShiftOS (UI.Themes.Importers.ShiftOS2017Importer/SkinData) (at Assets/Scripts/UI/Themes/Importers/IThemeImporter.cs:97)
UI.Themes.Importers.ShiftOS2017Importer/<Import>d__3:MoveNext () (at Assets/Scripts/UI/Themes/Importers/IThemeImporter.cs:63)
UnityEngine.UnitySynchronizationContext:ExecuteTasks ()
damn image processing is a pain in the arse in Unity sometimes D:
why does my temporary render texture have 11 mip levels
what if I only want one
what if it's a UI texture (it is) where mip maps are completely unnecessary
wait no the RT has one mip level but the destination Texture2D has 11
why
try setting the mip count on the constructor. I'm also not sure .LoadImage changes mip layout
I would debug log the mip count before and after to be sure.
In that case LoadImage is irrelevant. This is way after that, I managed to get around the error by switching to GetPixels
this new error is after I've blitted the images I need into a single 9-scale texture
That's done on the GPU into a render texture that I then blit over to a regular Texture2D
Can I see the code?
Nope :)
I just fixed it
eh I lied
// Step 2: Blit them
RenderTexture? rt = RenderTexture.GetTemporary(1024, 1024);
rt.BeginPixelRendering();
GL.Clear(true, true, default);
rt.DrawSprite(topBorderTexture, new Rect(skinData.LeftBorderWidth, rt.width - (skinData.LeftBorderWidth + skinData.RightBorderWidth), 0, skinData.TitlebarHeight));
rt.EndRendering();
Graphics.CopyTexture(rt, resultTexture);
RenderTexture.ReleaseTemporary(rt);
return resultTexture;
I did fix it but you can see it
this doesn't have the line where I create the dest texture
now it does
Texture2D windowBorderTexture = CreateWindowTextureFromShiftOS(skinData);
I have a coroutine that moves a rigidbody after yield return new WaitForFixedUpdate();
Works great unless I spam pause. Because then I end in the wrong position
How does pausing work in your game?
yes the function im spawning in is an async Task function. im awaiting some data then calling instantiate
- set Time.timescale to zero,
- Disable all monobehaviours on pausable entities (eg enemies, blocks, player), except those with a type on a blacklist. Eg colliders, physics mover, pause-controller itself…
there’s a bit more to it, but that’s the core idea
Then the issue isnt that objects are persisting, it is that you are spawning objects after play mode ends. Async has no care if you are in play mode
oh wow i get it. it indeed still instantiates after i enter playmode then quickly exit
@hard viper can I ask what the WaitForFixedUpdate coroutine is for?
My jump doesnt seem to work when pressing spacebar, but everything else in my code does seem to work. can anyone help me with this?
Here is the code:
https://paste.myst.rs/1gl822c7Everything
i dont think i really have another option with the cloud code sdk
Does it not work at all? Or only sometimes?
The jumping doesnt work at all
it’s job is to tell a rigidbody (equivalent sort of thing) to move a certain displacement each fixedupdate frame. Coroutine calculates how much to move, and tells rigidbody to move by that much
Everything else works fine
my other coroutines (which work fine) go to a specific target destination, but this one drives forward, and allows anything stopping it to reduce total movement
this is on purpose
Im unsure what cloud code sdk, I assume you could use a coroutine still or just check if its play mode somehow
but it’s like i miss a few frames
then you need to use cancellation tokens to stop the async method when you exit play mode. if you are using unity 2022+ then you can just use the destroyCancellationToken built right into MonoBehaviour
Maybe you could create a global "pause state" and check after the yield if that state is true, break out the coroutine, or continue to yield until the state is false
It's hard to tell exactly what's going wrong, but you'd get a lot more information by debug logging and seeing where exactly is doesn't trigger. I'd log your conditional bools and see if you ever get passed them. Something like:
`private void PlayerInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");//get keyboard inputs on horizontal axis
verticalInput = Input.GetAxisRaw("Vertical");//get keyboard inputs on vertical axis
Debug.Log($"Jump button = {Input.GetKey(KeyCode.Space")} | Ready to jump = {readyToJump} | Grounded = {grounded});
//checking if player hits spacebar key, if they do player will jump
if(Input.GetKey(KeyCode.Space)&& readyToJump && grounded)
{
Debug.Log ("passed checks");
readyToJump = false;//if player presses jump key, they are no longer ready to jump while in the air
Jump();//call the jump function which applies the forces
Invoke(nameof(ResetJump), jumpCooldown);//invoke the resetjump function and apply the jump cooldown, allows player to hold jump key
}
}`
Although, I have a feeling you might actually be jumping, but your grounding code just instantly snaps you back down to the ground. Either way, debugging like this will help you a lot to solve stuff like this.
I think it may be that
It doesn't recognize me jumping
It doesn't take in the jump Input
Do you see any syntax problmes
Input.GetKey should work, which is making me think it's a problem with how input is set up in your project. Unity has two input systems and it's pretty confusing to me actually, so I'm not an expert on the topic.
if you just log Input.GetKey(KeyCode.Space) it always returns false?
Oh, yeah, you should log all of the booleans going into your if statement to see why you're not getting there. So see which one out of those 3 (the Input.GetKey, the readyToJump and grounded) is false so you can't get to that jump function