#archived-code-general

1 messages · Page 229 of 1

swift falcon
#

thank you :)

#

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

hard viper
#

then I would avoid wall jump mechanics

swift falcon
#

so i want it to be as fluid as possible to be a stark contrast from the boring clicker

swift falcon
#

like in mario, you could wall jump onto their heads

#

which could damage them

hard viper
#

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

hard viper
#

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

swift falcon
#

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

hard viper
#

that doesn’t sound like a very good idea

swift falcon
#

they can take that path

swift falcon
hard viper
#

that’s just two different games

#

stitched together

swift falcon
#

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

vagrant blade
hard viper
#

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

hard viper
#

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

swift falcon
marble wasp
#

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

cosmic rain
marble wasp
#

and none of them are running consistently enough for that to happen

#

it's fairly consistent 2-3 seconds

cosmic rain
#

You're talking about that spike, right?

hexed pecan
#

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

marble wasp
#

looks like garbage collecter actually yeah

cosmic rain
marble wasp
#

oh actually that's others not garbage collecter

cosmic rain
#

And we need to see the hierarchy mode.

marble wasp
cosmic rain
#

Expand the player loop

#

Expand to the last biggest thing that takes CPU time.

marble wasp
#

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

cosmic rain
cosmic rain
#

Maybe adding/enabling new cameras or something?🤔

marble wasp
#

there are 3 cameras but i didn't enable anything

hexed pecan
#

Are you manually creating textures/rendertextures or anything like that?

marble wasp
#

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

polar marten
marble wasp
#

also worth noting that it doesn't always happen but i'm not sure what changes for it to start happening

polar marten
#

are you getting the colors of a texture for a postprocessing effect

marble wasp
#

kinda, i'm analysing the pixels of the texture but it's not consistent with the hitch

polar marten
#

okay

marble wasp
#

and it happens even with the script disabled

polar marten
#

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.

marble wasp
#

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

hexed pecan
polar marten
#

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

marble wasp
#

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

polar marten
#

anyway dont' stress this is all tractable to fix

marble wasp
#

yeah something i'll deal with later

polar marten
#

can you profile the standalone build and find what is actually taking a lot of time in your own scripts?

marble wasp
#

yeah building now

polar marten
#

it has a flow chart

marble wasp
#

man i wish they taught us this shit at uni lmao

cosmic rain
#

Most of developer's education is self learning.

polar marten
# marble wasp man i wish they taught us this shit at uni lmao

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

marble wasp
#

could be my shader, although this has been happening since before i made my shader

polar marten
#

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

marble wasp
#

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

polar marten
#

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

hard viper
#

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

marble wasp
#

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

polar marten
#

it's an editor issue

hard viper
#

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

polar marten
#

you also never showed the whole profiler hierarchy

marble wasp
#

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

upper pilot
#

If they object is destroyed/scene is changed does the UnnityEvent unsubscribe automatically?

leaden ice
#

If the publisher is destroyed, all the subscriptions go away
If the subscriber is destroyed, they do not go away

upper pilot
#

If my UI has:

Game.Instance.onGoldGain.AddEventListener(UpdateGoldUI)

will it RemoveEeventListener(UpdateGoldUI) when this UI element is deleted or scene changed?

leaden ice
#

what is "this UI element"?

upper pilot
#

so there will be an error if I try to Invoke the event and the subscriber doesnt exist anymore?

leaden ice
#

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

upper pilot
#

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.

leaden ice
#

Best practice is that if you do AddListener on OnEnable, you do RemoveListener in OnDisable

upper pilot
#

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.

hexed pecan
#

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...

upper pilot
#

my bad, a habit of making everything private 😄

cosmic rain
upper pilot
#

Thats what I do currently, I tried to follow the best practices, but it wasnt possible.

hexed pecan
#

Making everything private by default is good

upper pilot
#

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.

cosmic rain
#

Alternatively, use OnDestroy to unsubscribe as it's a closer counterpart to initialization

upper pilot
#

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?

hexed pecan
upper pilot
#

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

hexed pecan
upper pilot
#

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 😄

hexed pecan
#

Yeah, that's what I meant. Worth a try

upper pilot
#

Thanks, that should do the trick.

vocal drift
#

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());
    }
soft shard
# vocal drift bro, can someone help me with detecting joystick through script

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

leaden ice
#

Yes definitely use the new input system for whatever this is

vocal drift
#

aight thanks

valid nest
#

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?

latent latch
main shuttle
zenith atlas
#

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);
    }
}
short osprey
#

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..

somber tapir
onyx condor
#

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?

somber tapir
latent salmon
#

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 ?

hard viper
#

i don’t think that makes sense

somber tapir
hard viper
#

a scene is like a giant prefab that destroys everything you have loaded when you try to load it

fervent furnace
#

can application decide which physical monitor it shows on?
ask the OS to return a list of monitors attached to the computer and choose?

languid hound
#

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

rigid island
#

seems win32 specific

languid hound
mental rover
languid hound
#

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

untold siren
#

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)

latent salmon
latent salmon
rigid island
crisp bison
#

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?

next sparrow
#

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?

latent latch
#

Could just prefab them

#

and instantiate a whole new layout of em

hard viper
#

gridlayout has variables for rows and columns. You can just change rows=1 vs columns=1

latent latch
#

gridlayout pretty bad tho

hard viper
#

is it tho?

#

it works well for me

next sparrow
latent latch
#

it doesn't behave with content fitter and other ui components as you expect

next sparrow
#

But only in a special case.

hard viper
#

oooooh. yeah, that’s a problem

next sparrow
#

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

hard viper
#

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

next sparrow
untold siren
#

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

hard viper
#

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

next sparrow
#

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

hard viper
#

next suggestion: separate gameobject with the vertical layout group, then transfer all the children between the two objects

next sparrow
#

Because I wanted a longer width element, which I couldn't get in a grid

next sparrow
hard viper
#

that might be the cleanest and simplest way tbh

next sparrow
#

I think so

hard viper
#

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

crisp bison
#

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?

delicate trail
#

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!

crisp bison
# rigid island which toast?

Toast message on Android. Like the message that appears when you exit the application by pressing the back button,(tap again to exit)

long ridge
#

am I going insane? Why does the order of multiplication matter?

rigidbody.MovePosition(transform.position + movement * speed * Time.fixedDeltaTime);
leaden ice
#

and float * float is 1 operation

long ridge
hard viper
#

they should normally be pretty close to the same final result

#

but reducing total multiplications makes it faster

long ridge
#

Feels strange that it is like that but I also see why

somber tapir
#

it doesn't matter in almost any case

hard viper
#

vector3 * float * float costs 6 multiplications total.
float * float * Vector3 costs 4 multiplications.
The difference is like 8 ticks on a processor

long ridge
#

Isn't that something the compiler fixes?

hard viper
#

no

#

the order could matter

long ridge
#

In what way?

hard viper
#

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

knotty sun
#

Also what you are saying here
transform.position + movement * speed * Time.fixedDeltaTime
is
((movement * speed) * Time.fixedDeltaTime) + transform.position

hexed pecan
crisp bison
#

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)

tiny orbit
#

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?

carmine solstice
pastel patio
#

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...

leaden ice
pastel patio
#

I'm doing transform.position modifications.

leaden ice
#

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

leaden ice
pastel patio
#

So a character controller may only use CC.Move??

#

How is teleportation supposed to work in that case?

carmine solstice
#

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

fluid lily
#

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)?

carmine solstice
#

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

pastel patio
#

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?

pastel patio
#

Okay thanks

rigid island
#

it can be done within the same frame yes

carmine solstice
#

Yeah or just disable the whole CC that works too

fluid lily
#

Any news on C# .net6+ date? I am currently making systems that I wouldn't if I could just use microsoft.extensions

late lion
fluid lily
#

And webgpu?

tiny orbit
somber tapir
tiny orbit
somber tapir
tiny orbit
#

but the game exits fullscreen when the scene loads

somber tapir
#

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.

tiny orbit
spring creek
#

mkv requires a download

tiny orbit
# tiny orbit

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

obsidian imp
#

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;

main shuttle
wraith vector
#

Is this KiB per minute or second?

simple egret
#

Per "CCU" whatever that is

#

Hover the information icon on its right

wraith vector
#

ah, I guess the average consumption per second will need to be calculated manaully?

simple egret
#

Good question

gray mural
#

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?

somber nacelle
#

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

gray mural
somber nacelle
#

it's probably not great, but the alternative would be to wait until after the next physics update to perform the query

hard viper
#

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.

gray mural
gray mural
hard viper
#

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

gray mural
#

anyway, my gameobjects don't have rigidbodies..

#

maybe I should add some

hard viper
#

so they aren’t moving then

gray mural
#

sure they aren't

#

I wonder if I can achieve the same behaviour with 2D Rigidbody as without it?

hard viper
#

rigidbody is just a component to interface with unity’s physics system

gray mural
#

yeah, but adding it may cause me some issues

hard viper
#

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

gray mural
#

is there any way to sync a single transform ?

#

well, guess no

hard viper
#

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

gray mural
#

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 ?

hard viper
#

a kinematic rigidbody

gray mural
#

yes, but the colliders won't collide

hard viper
#

it would change behaviour in receiving callbacks, but you could use overrides to turn it all off

hard viper
#

you asked for moving colliders without affecting behaviour at all.

#

a kinematic rigidbody will do that

gray mural
#

No, I asked how to add a Rigidbody2D without changing my GameObject's initial behaviou at all

#

that includes all colliders collisions

hard viper
#

and that’s how you do it

#

you said you aren’t using any rigidbodies

gray mural
#

yes, I'm not

hard viper
#

ok. adding a kinematic rb will do that then

gray mural
#

Ok, I'll try it out. Thank you 😄

brisk shore
#

where can i learn how to structure the scripts and the general structure of my game?

gray mural
tawny elkBOT
#

:teacher: Unity Learn ↗

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

severe spire
#

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?

severe spire
#

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());

}

}

short osprey
#
[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 )

rigid island
short osprey
#

yes

rigid island
#

are you getting console errors?

#

OnDrawGizmos runs in the scene too

#

you are probably spammed with Null ref

#

lol

short osprey
#

im not getting Nullrefs

rigid island
#

oh wait the ifstatement nvm

simple egret
#

The Obvious™️, but just in case, the script is attached to something right

rigid island
#

thought it was a loop for some reason xD

simple egret
#

Then none of the if statements pass

#

Logging the collider type should tell you what it detected: Debug.Log(colliderComponent.GetType())

short osprey
#

but why? it is a box collider 2D? can it not see that?

#

sure lemme try

#

do i put that on the Start()?

simple egret
#

Yeah that's an option

simple egret
#

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)

severe spire
short osprey
#

oh

#

i misread ur sentence

#

hold on

rigid island
#

and you sure this possible, never tried forcing a cursor pos before so I'm not 100

simple egret
#

I'd make this easier and store the position as a variable, and add the vector input to that each frame

rigid island
#

is this same issue?

simple egret
#

Yeah, deltaTime is causing this

#

Dividing your numbers by a factor of 100

severe spire
simple egret
#

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

short osprey
# short osprey hold on

@simple egret Sorry, i got interrupted. it never seems to call the function, even before the if-statement

simple egret
#

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

short osprey
#

its not collapsed

severe spire
visual fjord
#

How can i do get value negative in the input with the new input system???

tiny orbit
# tiny orbit

still dont know what caused this... i had to go back to a previous commit and rebuild

soft shard
vernal wharf
#

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

rigid island
tawny elkBOT
rigid island
#

are the debugs correct ?

vernal wharf
vernal wharf
#

Would raycast be better?

#

Any solid examples anywhere I can copy?

rigid island
# vernal wharf Would raycast be better?

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

vernal wharf
#

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

rigid island
#

its pretty good approach as well

pine blade
#

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.

unreal temple
#

That's the easiest way using built-in stuff

#

If you have an RB just do that

leaden ice
#

e.g. for an enemy

#

hitObject.GetComponentInParent<Enemy>()

#

which has the added bonus that you should realistically only interact with the Enemy script anyway

unreal temple
#

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

pine blade
unreal temple
#

I wouldn't put a rigidbody on a level lol

leaden ice
unreal temple
#

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

pine blade
unreal temple
#

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

pine blade
leaden ice
#

it's almost definitely what you want

pine blade
leaden ice
#

it does the loop internally

pine blade
#

oh its part of the function

leaden ice
#

and it's not expensive unless your hierarchy is hundreds or thousands of elements deep

pine blade
#

oh ok thats easy then, thank you

pine blade
devout nimbus
#

Object getting stuck on walls even tho its radius is large and the wall is obviously a collider. Never had this issue before.

clever lagoon
devout nimbus
#

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

leaden ice
#

certainly sounds like a problem with the asset or how you have configured it.

devout nimbus
#

Yea messing with some things seems towork

spring creek
spring creek
upper pilot
#

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?

rain minnow
upper pilot
#

I cant seem to find a way to animate color with TMPro

#

Ah

#

CrossFadeColor?

rain minnow
upper pilot
#

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.

rain minnow
upper pilot
#

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()
rigid island
#

just use lerp or/and dotween

upper pilot
#

oh wow

#

Didnt expect "Mathf.PingPong" lol

rigid island
#

Mathf.PingPong helps with going back n forth

upper pilot
#

But thats what I need, thanks xD

novel bough
#

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

tropic surge
#

!ban @dull tulip bypass this ban

tawny elkBOT
#

dynoSuccess albiei was banned.

tropic surge
#

(note for future: sending CoD ban bypass exe virus)

loud wharf
#

Real.

waxen burrow
#

how would I go about extracting an animation clip from an fbx in script?

limber onyx
waxen burrow
# limber onyx 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

limber onyx
limber onyx
waxen burrow
limber onyx
short osprey
limber onyx
clever lagoon
waxen burrow
swift falcon
#

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

thin aurora
swift falcon
#

But I want it to wander around

#

And constantly revolve at random positions around the player

thin aurora
#

Around the player?

swift falcon
#

Yeah

#

Like a cool sword thingo

thin aurora
#

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

swift falcon
#

And just lerp?

thin aurora
#

And sine/cosine

swift falcon
#

I'll give it a go

#

Thank you

thin aurora
#

Combining those should give you a decent circle to work with

swift falcon
#

Yeah

#

Thanks man

#

Or girl

thin aurora
#

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

swift falcon
#

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

thin aurora
#

Yeah then just lerp it

swift falcon
#

Thanks

thin aurora
#

Lerp will account for the remaining distance so it might speed up/slow down

swift falcon
#

Yeah

iron sorrel
#

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.

teal stirrup
#

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

fervent furnace
#

what are the errors?

teal stirrup
#

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

fervent furnace
#

not your code?

teal stirrup
teal stirrup
limber onyx
fervent furnace
#

i have googled the script looks like it is vr chat

teal stirrup
#

I am a little confused by what you mean?

fervent furnace
#

somethings related to vr chat but i am not sure
havent tried it before

teal stirrup
#

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

teal stirrup
thick bough
#

If you have commisioned a VRChat avatar then you should ask in the VRChat server about uploading it @teal stirrup

thick bough
#

Then you don't need that script presumably? Can't you just delete it?

limber onyx
#

let me see

thick bough
#

No, VR Chat have their own discord server. We can't answer about it here

teal stirrup
teal stirrup
fervent furnace
#

!vrchat

tawny elkBOT
teal stirrup
#

I'll check it out ty for your time

fervent furnace
#

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.....

teal stirrup
#

I've contact the creator many times but have gotten no response

fervent furnace
#

oh i see.... he may busy/miss your request/ irresponsible...

teal stirrup
#

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

hard estuary
#

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?

hard estuary
knotty sun
#

then a Spline is probably your only other option

hard estuary
mortal tusk
#

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?

mellow sigil
#

Why would you use web requests to load local files in the first place

leaden ice
mortal tusk
mortal tusk
mellow sigil
#

Google for how to read files in C#. There's nothing special about it in Unity

#

unless they're files bundled with the game

mortal tusk
mellow sigil
#

why?

mortal tusk
# mellow sigil 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

mellow sigil
#

Ok, that makes sense. That can be automated too fyi

latent latch
#

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

mortal tusk
mellow sigil
#

Are you asking how to do it?

mortal tusk
mellow sigil
mortal tusk
prisma birch
#

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.

leaden ice
#

Then do the VS refactor

heady iris
#

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

hard estuary
# prisma birch What is the correct way to refactor a scriptable object without losing reference...

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.

heady iris
#

If the class name is wrong, it won't work correctly until you fix it -- but you won't lose the references

prisma birch
# leaden ice Change the name in Unity first

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.

leaden ice
hard estuary
prisma birch
heady iris
#

SO assets and component instances both use the GUID of the script asset to identify it

quasi adder
#

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 🙂

latent latch
#

Couldn't you just unormalize it by multiplying it out again -> compute then return as the expect value

leaden ice
quasi adder
fleet carbon
#

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.

rigid island
fleet carbon
#

Ooo thanks I'll check that out after work!

fervent furnace
#

what is "good use" btw.....
it is nothing more than a contiguous memory block....

fleet carbon
#

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 😂

rigid island
#

arrays go well with loops since thats one way you'd interact with all them at once

fleet carbon
#

Yeah

rigid island
#

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 🫠

fleet carbon
#

Yeah that's true, that Microsoft page you sent is quite useful tbh thanks for that

rigid island
fervent furnace
#

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
}
fleet carbon
# rigid island yeah microsoft really stepped up their docs/learning. It used to be ehh not so f...

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

rigid island
fleet carbon
#

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

scarlet viper
#

are null exceptions slow?

#

or are they the same as if i simply returned from a method (performance wise)?

fervent furnace
#

throw any exception slowing down your program

scarlet viper
#

ok

rigid island
#

u shouldn't ignore any NRE

fervent furnace
#

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
thin prism
#

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

fervent furnace
#

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.

hard viper
#

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

rain minnow
#

searching is your best bet (quickest route). it's not wasteful if you need it . . .

knotty sun
rigid island
knotty sun
hard viper
#

ty guys

#

ty guys. This is much better now:

wise escarp
#

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.

fringe ridge
#

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

fresh acorn
#

So I'm trying to randomize colors, how do I send the list values to the ballRenderer.color = someColor?

leaden ice
fresh acorn
#

Oh, let me fix that

leaden ice
#

Make a list of Color and just select one at random from the list

#

Assign it directly to the renderer

#

Done

fresh acorn
#

How do I make a list of colors?

fervent furnace
#

this is still list of string

leaden ice
fervent furnace
#

btw you know that goal is colliding with ball and why you want the goal finds another ball gameobject in your scene

jade kindle
#

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:

fringe ridge
# fresh acorn So I'm trying to randomize colors, how do I send the list values to the `ballRen...

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

rigid island
#

good advice ^

fringe ridge
#

this is just a rough idea of how i would do it, but i imagine it requires more work than this

leaden ice
jade kindle
fringe ridge
jade kindle
lean sail
leaden ice
#

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

fringe ridge
#

Well you could add a huge cost to turns

leaden ice
fringe ridge
#

so it tries to avoid it as much as possible

leaden ice
#

exactly

jade kindle
#

Then, I will try to implement on my own and I'll share the results. Thank you guys 😀

fervent furnace
#

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

fresh acorn
#

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.;

hard estuary
fresh acorn
#

Oh awesome thank you

#

Weird it randomizes to a clear color making it impossible to see on a black background

fervent furnace
#

the first choice is black

fresh acorn
#

Ohhhh lol

#

Thank you haha

#

Hmm the physics of my ball are off... after enough plays it will slow down. Any thoughts?

languid hound
#

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

fresh acorn
#

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.

mental rover
#

full Unity physics can be a can of worms when you just want some simple but crisp arcadey physics for sure

dusk plume
#

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

somber nacelle
#

it's likely due to the positioning of the gun

rigid island
#

probably non uniform parent

dusk plume
#

like this

rigid island
#

whats gun parented to ?

dusk plume
#

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.

rigid island
#

ohh maybe you scaled the player transform? idk its hard to tell from ss alone

lean sail
#

I would assume scaling, or the fov is changing. Not really much to say without seeing the setup or code

dusk plume
lean sail
#

Non uniform scaling results in weird things

rigid island
#

yeah its probably rotation skewing due to nonuniform

dusk plume
#

to uniform it

#

without changing everything

rigid island
#

dont scale the main gameobject

#

just scale the collider

#

main parent should only be a container not an actual mesh

dusk plume
rigid island
#

alr well dont scale transforms lol

#

well you can but non uniform will cause issues in children/rotations

dusk plume
thick socket
dusk plume
#

if i set it to 2

thick socket
dusk plume
#

it works?

thick socket
#

pretty sure I scale almost every transform highest parent lol

rigid island
thick socket
#

although ig mijne are uniform

rigid island
#

yes

thick socket
#

do you not scale like that specifically because of meshes?

#

aka Im fine to keep doing whatever since Im 2d?

rigid island
#

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

thick socket
#

how do you get the "titles" on here above the serializefields?

#

ex)SoundFx

#

(stolen img from @rigid island asset store page :D)

rigid island
dusk plume
#

i wish a good day to everyone 🙂

rigid island
thick socket
#

hmm something isn't working right

nocturne pollen
#

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.

  1. 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)
  2. 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.
  3. 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.

thick socket
#
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;
rigid island
#

don't think protected fields would show

#

so you need it to be above something that is serialized

thick socket
#

ah ok gotcha

nocturne pollen
thick socket
rigid island
thick socket
#

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;
rigid island
#

I'm gessing some shenanigans what that being a property

thick socket
#

very annoying

somber nacelle
#

much like the SerializeField attribute, you need to target the backing field for the Header attribute

thick socket
somber nacelle
#

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

latent latch
#

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.

hard viper
#

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

vivid remnant
#

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 :)))

leaden ice
vivid remnant
#

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.

somber nacelle
#

use Vector3.ProjectOnPlane and project the player's velocity on a plane with the ground's normal

vivid remnant
#

My thought process:

  1. I take the normal of the surface my character is standing on.
  2. I calculate the Cross Vector between the normal and characterTransform.right and store it inside a Vector3 instance called "direction".
  3. 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.

somber nacelle
vivid remnant
#

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!

languid hound
#

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)

vernal wharf
rigid island
leaden ice
languid hound
#

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

leaden ice
#

what makes you think it's null

languid hound
#

When I instantiate it gives a NullRef

leaden ice
#

what does

#

Maybe Camera.main is null

languid hound
#

I don't understand why it would be null though. I'll try spawning it at the player instead

leaden ice
languid hound
#

Ohh it has to have a MainCamera tag?

leaden ice
#

yes

languid hound
#

Okay fair enough I thought it was just the first active camera

#

That makes sense now

heady iris
#

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

#
                // 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

sleek chasm
#

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?)

hazy marten
#

did you get this script from somewhere? Sounds like you need a HandleAllInputs function that takes a type of InputManager

rigid island
summer oar
#

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

hazy marten
#

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?

sleek chasm
#

i did

sleek chasm
hazy marten
#

what does Assets\codes\PlayerManager.cs(17,22) look like?

rigid island
# sleek chasm

You should not name Classes the same names as Unity Classes

sleek chasm
rigid island
#

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

sleek chasm
#

thats the problem

#

cuz it exists

rigid island
#

!code

tawny elkBOT
rigid island
#

dont screenshot code

sleek chasm
#

okay

#

what should i do ?

rigid island
#

use the links

#

show full context of your code

sleek chasm
#

OKAY

#

done

sage oxide
#

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:

  1. Encoding the image to bytes and decoding it back to PNG/JPG when loaded.
  2. 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

simple egret
#

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

rigid island
#

and did you save/

sleek chasm
#

this is acctualy funny

#

cuz i didnt

#

xD

#

its working

#

thank you so much bro

rigid island
#

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

tawny elkBOT
rigid island
#

@sleek chasm

sleek chasm
#

thank you so much !

#

m still new to game dev

rigid island
#

all good! this part is important

#

saves soo much time and headaches later. You only need it once

#

goodluck 🙂

sleek chasm
#

Thanks dude cya

sage oxide
simple egret
#

FileSystemWatcher may not work on mobile, you might have to track changes yourself if that's a requirement

sage oxide
#

okay, thanks for the info!

summer oar
#

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)
hazy marten
# summer oar now I'm ust having trouble with this

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.

summer oar
#

Ignore that

ember mirage
#

anyone have an idea why prefab instances would persist after exiting playmode? re-entering playmode doesnt clear them either

summer oar
#

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

hazy marten
#

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?

summer oar
#

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

hazy marten
#

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

summer oar
#

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

hard viper
#

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?

hazy marten
hazy marten
hazy marten
summer oar
#

Yeah

lean sail
summer oar
#

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?

hard viper
#

I'm trying to figure out how to make my game more pause-proof, tbh

summer oar
#

solution: don't allow pausing /trolling

hazy marten
#

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

soft shard
heady iris
#

as in, resilient to being paused and unpaused?

#

so that it doesn't behave differently than if you hadn't paused at all

summer oar
#

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

hazy marten
#

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.

summer oar
#

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

hazy marten
#

Can I see the code?

summer oar
#

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);

hard viper
heady iris
ember mirage
hard viper
# heady iris How does pausing work in your game?
  1. set Time.timescale to zero,
  2. 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

lean sail
ember mirage
#

oh wow i get it. it indeed still instantiates after i enter playmode then quickly exit

lean sail
#

That is one main reason async is not preferable

#

And generally u dont need it

hazy marten
#

@hard viper can I ask what the WaitForFixedUpdate coroutine is for?

obtuse cape
ember mirage
hazy marten
obtuse cape
#

The jumping doesnt work at all

hard viper
obtuse cape
#

Everything else works fine

hard viper
#

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

lean sail
hard viper
#

but it’s like i miss a few frames

somber nacelle
soft shard
hazy marten
# obtuse cape The jumping doesnt work at all

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
}

}`

hazy marten
# obtuse cape The jumping doesnt work at all

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.

obtuse cape
#

It doesn't recognize me jumping

#

It doesn't take in the jump Input

hazy marten
#

Did you print the results? What did it say?

#

the Input.GetKey stuff didn't work?

obtuse cape
#

No it didn't work

#

I debug logged it

#

The inputs don't pass

obtuse cape
hazy marten
#

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.

obtuse cape
#

No it's not anything to do with that

#

I'm following a tutorial

hazy marten
#

if you just log Input.GetKey(KeyCode.Space) it always returns false?

obtuse cape
#

I logged it like that

#

I also logged the grounded code and it doesn't seem to work

hazy marten
#

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

obtuse cape
#

Yea the code doesn't recognised I'm grounded

#

Can u see any problems in thr grounded bits of thr code

#

That is thr ground properties

#

Inspector