#archived-code-general

1 messages · Page 172 of 1

night harness
#

I had a lot of messy scattered functions that I felt bad about and then just randomly realised hey all of this could be in the data class im constantly using

#

I think I just forgot non monobehaviour classes can still have custom functions 😭

#

btw personal shoutout to all the help you keep giving me @pure cliff, Really appreciate it

worn stirrup
#

this positive space issue with rigidbodies is driving me nuts

#

how the heck do I convert half a set of negative converting rotations to work with a postiive-only 360 area

worldly hull
#

Math.Abs?

#

let me see if i can work it out

vivid raven
cosmic rain
worn stirrup
#

I nabbed a positive clamper to help with this, but I'm still not understanding how to get what I'm looking for...

worldly hull
#

u have a spawner A that spawn coin spawner B , and then coin spawner B spawns coinA

#

why dont u let coin spawner B spawns the coin instead

#

why add a step on top of this?

vivid raven
#

the randomized spawner make 1000 instanses in a random patern in my world

pure cliff
warm geyser
#

Hey if anyone knows, I am trying to lerp the Color32 property of a material on a particle system and it's just seemingly doing nothing.
Code is relatively straight forward:

pure cliff
#

I think my next blog post I gotta sit down and do is a write up on how to smoothly integrate Zenject with the "new" InputSystem, including if you wanna support using multiple players

night harness
#

yooooo

#

good looks on the blog!

worldly hull
worldly hull
#

if randomized spawner make 1000 random objects spawned,

just spawn the coin instead

vivid raven
#

well i want when the coin is collecnted it to respawn after a certian amt of time

worldly hull
#
  1. make an array of gameobject prefab

  2. use random.range to pick random object from the array

  3. spawn out the object

#

one spawner is enough

cosmic rain
vivid raven
cosmic rain
warm geyser
#

I'm not lerping wrong at all, that's a technique to create a gradual interpolation using Lerp

worldly hull
#

it will work, i just think adding up a second layer of spawner with no specific reason is quite pointless

warm geyser
#

I figured out the issue, it's actually just to do with Unity's particle renderer. Even without code influencing it, I cannot change a material property on a particle system during runtime.

leaden solstice
worldly hull
#

i will work on it lol

vivid raven
warm geyser
cosmic rain
night harness
#

Speaking of lerping, what's the ideal method of using a lerp to make a number transition from a to b at a consistent rate

worldly hull
#

right?

cosmic rain
#

No

#

don't use delta time as the third param

vivid raven
pure cliff
#

or wait no derp

leaden solstice
pure cliff
#

you want uh, += delta time on some var you track

#

Im thinking of that other method which takes in the old val and new val out var and delta time, I forget what that one is

warm geyser
#

Lerp aside, it's not the root of my problem

leaden solstice
worldly hull
# vivid raven ye something like that. now i just gota imploment it

tell me more of the respawn mechanics

1. spawner spawns x coins at first (like 10)
2. if one of the 10 coins get collected , spawn more, keep the amount at 10```
```markup
1. spawner spawns x coins at first (like 10)
2. spawns a new wave of 10 coins once all collected```

```markup
1. spawner only spawn 1 coin
2. coin is respawned once collected```
#

which one u want?

warm geyser
#

I'm basically trying to fade out a group of existing particles before I disable the parent game object

vivid raven
worn stirrup
#

Okay so I've got it to work (will gif once I get the other arm to work and maybe fix the dang controls), but also this issue is making me clamp my angles so much, AND I had to modify it to clamp 1-360 instead of 0-359, and since this is ALL due to the fact that I'm rotating back and forth from 0, I might just make some parenting edits later to make it wiggle around 180 or something

leaden solstice
worn stirrup
#

clawLeft.AddTorque(clawArmSpeed * (1 - Mathf.InverseLerp(ClampAngle(-clawLimit), ClampAngle(clawLeftGhostRot), clawLeftRot)));

#

Legit clamping two of the three inputs to make it all work with RB physics

warm geyser
#

I don't use SmoothDamp that often but does it work the way that Lerp technique works where it's almost a logarithmic apporach to the destination?

leaden solstice
pure cliff
#

If I were to tackle it in an async way Id prolly do something akin to

private async void LerpAsync(float a, float b, float duration, Action<float> callback) {
    var time = 0.0f;
    while (time < duration) {
        var lerp = Mathf.Lerp(a, b, time / duration);
        callback(lerp);
        await Awaitable.NextFrameAsync();
        time += Time.deltaTime;
    }
}

And then invoke it along the lines of:

private float SomeTrackedValue;

private void OnSomeEventOrWhatever() {
    LerpAsync(1.0f, 5.0f, 3.0f, v => SomeTrackedValue = v);
}
#

Can do the same thing with IEnumerator and StartCoroutine, it pretty much works the same way

leaden solstice
#

That's the point that you'd just use tween library

pure cliff
#

yeah its my understanding that lib basically has methods much akin to what I just wrote

#

I typically spin my stuff up myself on the fly as needed, because its usually faster than fussing with libraries if its a pretty simple implementation

worn stirrup
#

I hope wytea's still awake cuz it took forever but his idea worked lol

prime sinew
#

oh it worked?

lean sail
#

Kinda just trying to get some opinions here:
I have different scenes with some UI that can be toggled on/off, like a main menu, settings, etc. I initially wrote some basic code, script takes a button, on click set everything to inactive then set relevant ones to true but this obviously cant be reused.

Started writing some code to handle this, now my code holds a list of UIStates which is intended to be set in inspector. Each UI state has a "state" and a list of stuff it wants active but now im not sure the best way to declare what a state is, since its no longer just a premade enum. I initially stored these states as a string, but that just doesnt feel right. Should I just use scriptable objects instead of a string, so anything wanting to modify the state can just have an SO plugged in?

worn stirrup
# prime sinew oh it worked?

So far so good! the biggest annoyance for you to keep in mind is if you're working with RigidBodies, going past 0 auto-loops to 360, so you have to have a method to clamp too big/small values into that range

#

And for that reason, I'd rather put a parent on the object that rotates it 180 degrees, then locally re-rotate it back up, so can use local rotation to workwithin the 180 degree 50 degree area instead of flipping between signs at 0

#

I'll show that when I fix it, but I'm stubborn and want this bad physics code to work first

#

Then I'll fix it 😛

cosmic rain
worn stirrup
#

nvm this clamp code officially don't work for the other arm

lean sail
worn stirrup
#

ugh uguu errored so here goes gfycat

#

10 years later....

vivid raven
#

oh i already figured it out, i just need to switch what object the randomizer spawns, sorry for making u do all this work

cosmic rain
worldly hull
#

randomrange handles all the work

lean sail
vivid raven
# worldly hull randomrange handles all the work

reading over what u made that 100 times more complicated then what i can come up with, but ty for helping with the idea of respawning the coins, i even think its more intresting cuz you cant afk in that one spot waiting for a coin to respawn

worn stirrup
#

good god

#

direct link isn't good for streamable

#

let's try once more lmao

cosmic rain
# lean sail the naive approach i wrote before is like basically hardcode <https://gdl.space/...

I think the issue is probably with you mixing up UI windows and game screens. For example, a lobby menu should be a separate screen with it's own unique ui windows and ui management. While friendsListUI should probably be a window that can exist in a certain(or several) screen. When switching between screens, you would disable other screens and consequently the ui windows that belong to it, while enabling the new screen with it's windows. While in a certain screen, different windows belonging to it, can be toggled on and off.

worn stirrup
#

The right one doesn't work, time for an hour of fixing

cosmic rain
prime sinew
#

and can the claw be asked to close midway of closing

#

or is it always the full range of motion

#

it looks cool btw

worn stirrup
#

I am obsessed with physics games, I'm making a space game about pulling objects out of orbit, with different weights, sizes, so hooking an only-so-heavy crane around and yanking them out of orbit is kinda the idea

prime sinew
#

sounds fun

worn stirrup
#

making/doing the trash was the fun part, if I started with the crane I would've given up xD

#

none of these textures are mine, but this is a prototype

lean sail
# cosmic rain I think the issue is probably with you mixing up UI windows and game screens. Fo...

im unsure what you mean with different screens, right now this script is just in its own scene and theres only really 4 objects that im toggling on/off. The objects are also parents of some UI, so InLobbyMenu is a parent object that contains children of a button, labels, and will contain the list of current players.
I realize I also dont even need to include the friendsListUI since its toggled in both states

#

I feel thats somewhat similar to what youve described, but if i treat being in a lobby and outside a lobby as different windows entirely, wouldnt that just mean I need to duplicate things that exist on both

cosmic rain
# lean sail im unsure what you mean with different screens, right now this script is just in...

Okay. I guess I made some assumptions that were not actually true.
By different screens, I assumed that you have like a log in screen, in game ui screen, shop ui screen, etc. Kind of separate ui spaces if that makes sense.

As of now I don't see much point in a complex system. Just hardcoding stuff is good enough. Later, when if you feel like you're starting to write repetitive code, you might want to consider refactoring things - pulling members from your existing ui script into a base class and extending it for different screens.

cosmic rain
lean sail
#

Yea ill just stick to this easy method then, i was kinda reluctant with SO as states because it also just feels weird

lean sail
night harness
#

@lean sail I think last time I wanted to do this but not spend too much time on it I did something super yucky like this

#

dunno if it helps at all, just a psycho take

lean sail
night harness
#

Fair, depending on some situations you might want the ability to specify but def. not necessary

lean sail
#

well im no longer going with this solution but what I did was this on start

        // Get all unique elements to avoid setActive repetition
        foreach (var uiElement in uiStates)
        {
            foreach (var element in uiElement.activeUIElements)
            {
                if (!allUIObjects.Contains(element))
                {
                    allUIObjects.Add(element);
                }
            }
        }

so it only disables things already "registered" in a UI state. Not like everything on the canvas

worn stirrup
#

bruh why it takin 20 sec to complete domain with 4 scripts

#

is it the mobile SKDs e.e

#

the 180 thing was easier than I thought, now it's just on to arm 2 again

night harness
worn stirrup
#

thank you

night harness
#

In Project Settings -> Editor.

Read up on the settings though because they do cause problems with certain things

#

Enter Play Mode Settings needs to be ticked for the other two to have control, so having the latter two be false disables the reloading

valid raven
#

Asking for help from an amateur dev here-

I just started learning how to code and bought few templates to help me get jumpstart with prefabs and all. Been learning how to set up PlayerMovement since last couple of days. My issue since lately is the code I am following and learning
from had vanish or disappear for "death" while I had body dies lie there and set as static, but it can still flip x going left or right while lying there static. Kept getting error message which is because of the dead body moving left and right, assuming. If anyone knows what's the code to add or suggest would be greatly appreciated.

#

Oh to clarify, I am doing 2d platform game

prime sinew
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

prime sinew
#

You set your rigidbody to static when it dies, but you still are setting it's velocity which you shouldnt because static rigidbodies don't move. That's what the error is complaining about

valid raven
#

Yeah

#

and I have visual studio no?

prime sinew
#

The issue is, in your Update where you set the velocity, you don't have a check to see if you're dead

night harness
prime sinew
#

It doesn't recognize Unity properties

night harness
#

Also worth dropping the bot message about sharing code too (i dont know the command)

valid raven
#

oh ok so i need to download it on unity to have it connected simultaneously?

prime sinew
#

It's almost Microsoft word at the moment

#

No

valid raven
#

I thought they were already, ok

prime sinew
#

Please

#

Click the link

#

It'll walk you through how to configure

#

Either way I've pointed out your possible issue

#

Probably need a boolean that is set when you die

#

Then your Update can check that boolean before attempting to set the velocity

valid raven
#

ok thank u

prime sinew
#

I just stress that having a configured IDE is a requirement to get help here, simply for the sheer amount of silly mistakes it prevents

valid raven
#

sounds good

night harness
#

Your question was well typed btw, good amount of information. a lot of people struggle with that

prime sinew
#

yep, supplying the error message and the code is appreciated. in the future, do follow this guide on how to share code though

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

prime sinew
#

@valid raven

worn stirrup
valid raven
#

yeah truth be told i m bit lost, completely new here.

mighty yew
#

I'm not really sure if this is possible or not, but I want to "replace" certain animations with other animations in my animator through code. Like normally its animation one, but when an event happens it becomes animation two? both animations will function nearly identically and will just look different. Is there any way to do this?

night harness
#

Nah your doing fine homie. Just once you get your visual studio hooked up nice and know how to share code nicely it's like 100x easier for people to help you out

prime sinew
worn stirrup
valid raven
mighty yew
#

which component is animationClip?

#

the actual animation gotcha

worn stirrup
#

My bad, it's something you can program with

mighty yew
#

no you're fine it was my misunderstanding

prime sinew
#

if done correctly, it'll be underlining errors and autosuggesting properties

valid raven
#

ok got it

#

thank u

prime sinew
#

you're welcome

worn stirrup
#

Every time I start a project and open and don't have syntax highlighting

#

I scream

#

And then I fix it because I need the extra pretty colors to code good

prime sinew
#

check out this resource too if you're stuck sometimes. it's made by vertx who is one of the mods here. we frequently point to this for frequently encountered issues
https://unity.huh.how/
@valid raven

#

best of luck

valid raven
#

ok so i checked, I already had it installed in unity and all

prime sinew
#

can you show a screenshot of your IDE then?

#

the point wasn't to have it installed in Unity. it's not even installed in unity. it's a separate program that can be configured to work with Unity

valid raven
#

where do I find IDE?

prime sinew
#

your IDE is your visual studio

#

IDE is the program you use to write code in

valid raven
#

ok it's in 2nd image that I posted earlier?

prime sinew
#

i want to see the current state

#

to see if it's configured

#

which is the entire point of this convo

valid raven
#

is this ide?

prime sinew
#

yep

#

looks good. it's configured now

#

now when you type, you'll see the red underlines if there are errors

#

and it'll suggest unity stuff for you

valid raven
#

ok i tested again, still have an issue, it's the velocity that says i m not supposed to be flipping when i m in static phase (dead)

#

so i m trying to figure out if it's a new code to add in playerlife script or fix somewhere in movement like disable movement while dead?

prime sinew
#

i already told you

valid raven
#

like die = movementstate = false?

prime sinew
#

you need to set a isDead boolean to true when it dies, and only set the velocity if the boolean is false

valid raven
#

I added "bool _active = true" then last 3 with this-

private void Die()
{
rb.bodyType = RigidbodyType2D.Static;
anim.SetTrigger("death");
_active = false;

#

thoughts?

#

no errors in visual but still same issue in unity

#

regarding static body that is

#

trying to figure out how to make _active works itself without rigidbody to static

prime sinew
#

Where did you use it to make sure velocity is only set when it's true

ebon panther
#

hi so I've been using this basic coding site called "scratch" for a while, any good ways to transition from scratch to unity?

prime sinew
#

If you don't understand that, please, you would benefit from the beginner stuff in Unity Learn

#

And an introduction to c# tutorial

#

find the line that sets velocity

#

then wrap that in an if statement that makes it so that it'll only run the velocity setting line if your _active is not false

#

since you set it to false when it's dead, and you don't want it to set velocity when it's dead

unique robin
#

There is something wrong with my Input detection. I have done lots of debugging and the input is the direct problem. I am aware FixedUpdate can't detect GetKeyDown and GetKeyUp however if i call for GetKeyUp in an update method, set a variable for true if so, and then set that variable to false after uisng it in FixedUpdate, the input should register. However litterily a basic GetKeyUp or even GetAxis doesn't work in the update method

unique robin
#

Wait I wills et up example script and see what happens

warm night
#

Hey, I'm a beginner at Unity Netcode (btw i didn't see any channels for that so thats why i'm posting this right there), I want to have a GameObject (or a transform, or even a script, idc) to pass a gameobject through a clientRpc method, is that possible? because i got some errors that gameobject cannot be passed through clientRpc methods :/

unique robin
#

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

public class Script : MonoBehaviour {
void Update() {
if (Input.GetKeyUp("w") || Input.GetKeyUp(KeyCode.UpArrow)) {
Debug.Log("hm");
}
}
}

#

I will spam w or up arrow and nothing is in concole

elfin quest
warm night
#

oh, okk, i saw the invite, but ok thanks i'll search with this

warm night
elfin quest
unique robin
prime sinew
#

are there compiler errors @unique robin

warm night
#

maybe in player prefs ?

unique robin
warm night
#

like the basic input

#

or the qwerty keyboard, i already had this problem

unique robin
#

This is kind of related to #🖱️┃input-system but if I have a verticle axis does that get rid of all kets attatched tot hat axis for GetKey

prime sinew
#

are you using the new input system, or the old input manager

#

you should clarify that

#

@unique robin

unique robin
#

I am not sure haven't uopdated in a while

prime sinew
#

find out

#

google how to find out what you're using in your project

unique robin
#

I am pretty sure I am using new input system

prime sinew
#

did you check?

unique robin
#

using unity 2021.3.5f

prime sinew
#

that does not matter

#

your unity version does not matter. it's what your project is set up to use

unique robin
#

I often use the old input system so potentially I'm not using the new input system and trying to use the old

prime sinew
#

Check what you're using now

#

Is the object this script is on active

#

If you debug log in the update, outside the if statement, does it print

#

In this complete quick-start guide, you'll learn everything you need to know to get started with Unity's new Input System, step by step.

scarlet viper
#

ComputePenetratoin - if the output distance variable is above 0.0f then there was no penetration ?

late lion
#

The method returns a bool for whether there is any penetration. If it's false, then direction and distance are not defined, but probably both zero.

scarlet viper
#

it works now thanks

keen solstice
hexed geode
#

what i want to do is to instantiate a series of gameobjects which have buttons in their children objects, and then make them call a function on click which will have a parameter based on their order:

private void Start()
    {
        for (int i = 0; i < SkinInfoHolder.instance.skins.Length; i++)
        {
            GameObject createdSkin = Instantiate(skinPrefab, grid);
            createdSkin.GetComponent<Image>().sprite = SkinInfoHolder.instance.skins[i];
            createdSkin.GetComponentInChildren<Button>().onClick.AddListener(delegate { PickSkin(i); });
            buttons.Add(createdSkin.GetComponentInChildren<Button>());
        }
        UpdateButtons();
    }

what happens, is that the gameobjects and the buttons do get created and added to the list, but they don't do anything on click. i tried doing createdSkin.GetComponentInChildren<Button>().onClick.AddListener(() => PickSkin(i)); as well, but that didn't work either. am i doing something wrong?

leaden ice
#

which is the classic lambda variable capture bug in a loop

#

you need to do this:

int localI = i;
createdSkin.GetComponentInChildren<Button>().onClick.AddListener(() => PickSkin(localI));```
#

otherwise all of the buttons will reference the actual i variable which by the end of the loop will == SkinInfoHolder.instance.skins.Length

hexed geode
leaden ice
#

listeners added with AddListener don't show in the inspector

hexed geode
#

oh, i see

#

havent worked with listeners basically ever, never knew that, thank you!

leaden ice
austere oriole
#

Hey guys
I was making a character creation screen, I can chose between female/male at the moment but in a later fase I want to add stuff like races, hairstyles, haircolour, skincolour. Someone told me to put them in variables and use playerpref to save those variables. For example, male and female would be at the top. if you press male, you get for example "int gender = 1", then you could go to races and click the race "human" you'll get a male human, if you click elf, you'll get a male elf and so on. For hairstyles then for example, if you picked male gender (1) and human race (1) you'll only get the hairstyles for that specific number (1,1). let's say you picked male gender but for example demon race (int 4 as example so you'll get, 1,4) you'll get hairstyles for that specific gender and race like horns, and so on

Another guy told me to make classes in unity for each variable. but I guess all classes also use an numeric index so it works the same but different?

Is there anyone who's willing to put me in the right direction, maybe with an example script or something? I think I can script the first way myself, with a bit of thinking, I just don't know if its the right way to do it. I don't know much about the classes system tho.

west sparrow
# austere oriole Hey guys I was making a character creation screen, I can chose between female/ma...

I'd probably use an Enum for the types, I.e. character classes.

public enum CharClass {
  None,
  Warrior,
  Archer
};

Then a base data type, could be an SO.

public class CharClassElement {
  public CharClass = CharClass.None;
  public int Power = 10;
  ...
}

Then from there, either use the generic as a base data type or use inheritance for class specific code. You shouldn't really need to do that for base stats or base character design though.

mellow vapor
#

what .net sdk should I download?

west sparrow
#

But an enum is essentially an int with a human readable name.

west sparrow
austere oriole
#

But I don't really get the classes, how do I save the different hairstyle assets to it for example :c

#

How do I even get the hairstyles to fit on the head where they are supposed to be and how do I save everything so that the player go's into the game with the customised character and keeps it when loading the save file again

#

:p scripting is hard

rancid jolt
#

I want the cursor to be invisible on a particular scene. But it is getting invisible only if I lock the cursor state which I can't do because of the nature of the gameplay. Is there a way to do it without locking the cursor?

late lion
candid kiln
#

no more logs, i'm pretty sure there is only one instance

late lion
candid kiln
leaden ice
#

not 264

#

and it's likely the line of the Debug.Log in your catch block

candid kiln
leaden ice
#

anyway - it's pretty clear blockSprites is not assigned

devout harness
#

I noticed accessing the rotation.eulerAngles.x of a transform returns strange results. I'm getting something like:

leaden ice
candid kiln
#

it logs the item count in list

#

not the line of error

leaden ice
leaden ice
leaden ice
candid kiln
#

because i've added a line to log something else

#

it's the same line

leaden ice
#

one issue here is your use of the ?? operator

#

that doesn't work properly with Unity objects like Texture2D

candid kiln
#

hold up

#

lemme try something

rancid jolt
devout harness
knotty sun
leaden ice
#

or use Vector3.SignedAngle to get the proper angle

candid kiln
#

this got it fixed, thank you @leaden ice

devout harness
rancid jolt
devout harness
rocky helm
#

How should one approach making an NPC script which, in a nutshell just wanders around and runs from the player when the player is holding a gun? I've tried making something like this that I could build up on two times now, but both have come out pretty ugly and hard to use.

dawn mauve
dawn mauve
# rocky helm How should one approach making an NPC script which, in a nutshell just wanders a...

https://github.com/ashblue/fluid-state-machine

Here is a library if you just want to get started. Ashblue is amazing. He also has a behavior tree library in case you wanted to go that route.

Though for your simple AI I’d stick with FSMs

GitHub

A finite state machine micro-framework for Unity3D focused on a pure code implementation. - GitHub - ashblue/fluid-state-machine: A finite state machine micro-framework for Unity3D focused on a pur...

#

GLGL

hard viper
#

I have a SO for entityData that tells a given gameobject what sorts of things it should be vulnerable to (ie fire, spikes, stomp, etc).
I want to be able to keep something mutable during runtime so that the vulnerability of an individual gameobject might change during runtime (eg Koopa shell does dmg to player when in a moving state, and not when stationary).

Differences during runtime might be very small. Does anyone have a suggestion for how to handle this with minimal code repetition?

#

i feel like there is going to be a good design pattern for this.

knotty sun
#

Mutable ScriptableObjects at runtime

leaden ice
hard viper
#

i see. and I would need to use reflection to make a deep copy? which I assume is what steve’s package does automatically?

heady iris
#

and to track any modifications to that base state separately

leaden ice
#

How deep of a copy do you need?

heady iris
#

Alternatively, the SO is just used to construct the runtime data

#

I would do the former if I was clearly just making additions to the base state

#

and the latter if the fundamental properties were changing

hard viper
#

i do not know yet. I would start by assuming a complete deep copy. everything in it should be value type. ints, bools, enums, and a couple of strings

heady iris
#

"Deep copy" means that references are also recursively copied

hard viper
#

changes are only applied to an instance, so I want to keep the original under lock and key

heady iris
#

from my experience, when you ask about how to do a "deep copy", you're doing something the hard way

hard viper
#

there are no references in this SO

#

only value types

leaden ice
hard viper
#

i see. would it automatically get destroyed/garbagecollected when done?

heady iris
#

as always

leaden ice
#

No, you will need to call Destroy on it

heady iris
#

oh right, yes

leaden ice
#

in OnDestroy

heady iris
#

after you destroy it

#

i forgor

leaden ice
#

Since it's a UnityEngine.Object

heady iris
#

It wouldn't die during a scene switch, right?

hard viper
#

this feels a bit dangerous, but I can handle that. I mostly want there to be zero chance of ever modifying the original

heady iris
#

since it's not part of a scene

hard viper
#

maybe I should make a childclass of my SO to avoid getting tripped up?

heady iris
#

that is one option

#

Copy<T> where T : ScriptableObject

hard viper
#

like EntityData: SO, RuntimeEntityData : EntityData.
RuntimeEntity data is mostly an empty class

heady iris
#

it'd have a constructor that takes a T and instantiates it

hard viper
#

hmm, maybe I should look into stevie’s package.

knotty sun
hard viper
#

ok

#

i gtg in 3 min tho

primal wind
#

Can you not cast an UnityEngine.Object to Sprite?

#

I'm doing that but it just fails

knotty sun
#

Object as Unity.Object or System.object?

primal wind
#

Corrected

#

Unity ones

knotty sun
#

No, Sprite is not a UnityEngine.Object

primal wind
#

Oh

#

Well back to the drawing board

knotty sun
#

use System.object, will work

#
object o;
Sprite sprite;
if (o is Sprite) sprite = (Sprite)o;
leaden ice
#

Can you explain what you mean by "it just fails"?

primal wind
#

I think it actually is a Texture2D

#

i'm gonna test that

leaden ice
#

If your object is not actually a Sprite then it will fail

leaden ice
primal wind
#

yup it was a Texture2D

#

Now it works

knotty sun
#

which you are trying to make a Sprite from?

leaden ice
primal wind
#

I did

#

I was trying to assign it to an Image directly out of the method that casted it

#

Now it works

leaden ice
#

not sure I totally follow but, glad it's working 👍

knotty sun
#

if it's similar to the problem I recently encountered, Sprites are not included in the AssetDataBase but the Textures they are created from are

primal wind
#

I guess it would work if i make a Sprite field and put it there but that would make my thing a bit less unified

#

I don't even know if what i did is useful

sudden meadow
#

Any idea why this is all of a sudden causing Unity to take 5 minutes to reload script assemblies?? I haven't even changed this today and it was working up until now when it started acting up out of the blue.

I tried changing only LoT_Animation to Serializable but it still happens.

#

Do I have to switch to serializefield or something

late lion
sudden meadow
#

@late lion sorry I dont know what the yaml means or how to check this

knotty sun
hard viper
# leaden ice one option is: ```cs public MyScriptableObject mySo; void Awake() { mySo = In...

I’m thinking more about this. My SO has every field with public get, private set (so it doesn’t accidentally get altered), but I then want my copy to be mutable.
Would it be best to make them protected setters, and use a child class where everything is public?
And child class uses reflection to make a copy of the original fields into itself. I think this is right, but I want to ask before granting write access when readonly files are involved.

sudden meadow
#

@knotty sun oh ok I see. I'll try that.

#

Doesn't seem to make much of a difference. Actually hold on

late lion
sudden meadow
#

Wait on the AnimationFrame? But it's a struct and can't have a parameterless constructor. Maybe I should just make it a class

#

It's saved in a scriptableobject

#

perhaps i can open that like a prefab

late lion
#

Yes, you can open the .asset as a text file through any text editor, like Notepad.

#

Assuming you have text serialization enabled instead of binary.

leaden ice
#

you can mark the fields as protected

hard viper
#

but then how would I allow other classes to modify the child

#

but not the original

leaden ice
#

through public properties on the child

hard viper
#

in that case, I need to maintain it so whenever I add fields to the original, I also need to add fields to the child

leaden ice
#

you can also turn this whole thing around - you can make an interface like ReadOnlyThing which only exposes getters and not setters

#

then you don't need a child class

#

pass the SO around as that interface in places where it shouldn't be mutable

dire crown
#

That's what I do as well

#

Interfaces 👍

sudden meadow
#

I am simply storing sprite references in scriptableobjects

hard viper
#

if the original is in a class with public setters, then I am at risk of forgetting, accessing it through not the interface, and changing the original

sudden meadow
#

if i don't serialize i can't see it in the inspector

late lion
sudden meadow
#

yeah

knotty sun
#

Maybe silly question but have you defined your own Sprite class?

sudden meadow
#

I haven't no

late lion
knotty sun
#

its part of his struct

late lion
#

Oh, my bad

sudden meadow
#

yeah it's just an int in the struct

knotty sun
#

can you screenshot the inspector for the SO

sudden meadow
#

yes just give me 5 minutes for the rebuild to finish timing out

knotty sun
#

lol

#

in the meantime, which Unity version?

sudden meadow
#

2021.3.24f1

#

and as I said it was working fine until just now, and I haven't changed this class today. So I might go back and try reverting some stuff I guess if all else fails.

knotty sun
#

can you please post your code to a paste site
!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

lone dawn
#

So I made a moving platform script that uses transform.SetParent on the character controller.
It works but only manually? Like when I change the position of the platform with code it slides below the player, but when I manually change the location in the editor it works? Any help?

late lion
heady iris
#

character controllers get mad when parented, don't they

sudden meadow
#

I could try nuking the library folder

heady iris
#

I would do that

#

especially if you've ever force-closed the editor

#

you can get some Weird Cruft in there that makes the editor misbehave

sudden meadow
heady iris
#

random errors that make no sense

sudden meadow
#

this is the SO

knotty sun
lone dawn
heady iris
#

so we aren't seeing the actual problem

#

I see no reason for this to happen, so i'm blaming library demons

knotty sun
heady iris
#

we're brushing up against one of the two hard problems of computer science: cache invalidation

sudden meadow
#

rebuilding the library now i'll get back to you

knotty sun
sudden meadow
#

It seems to work fine now

#

Not complaining about the serialization depth either

#

so I guess it was a library quirk

late lion
#

Maybe you accidentally made a circular reference in LoT_Animation for long enough to cause a recompile and mess up the cache.

#

I would have expected that Unity can recover from that, but 🤷‍♂️

sudden meadow
#

Well, it seems fine now so thanks for the help 😄 Ping me if you want any follow up info, otherwise I guess I'll be back of it comes back soon lol.

knotty sun
#

@sudden meadow Works for me so i guess it was just a wierd bug

sudden meadow
#

Yeah seems like

heady iris
#

but at a high level, the Library is just a gigantic cache

#

all kinds of stuff generated from your Assets (and from packages)

#

i suspect that crashes or freezes that end with a SIGKILL can leave it in an inconsistent state

#

unity doesn't understand that it needs to regenerate that data, but the data is bogus

#

also, augh

#
Message: Build asset version error: assets/scripts/monobehaviours/debug.cs in SourceAssetDB has modification time of '2023-08-15T16:07:46Z' while content on disk has modification time of '2023-08-15T16:08:15Z'
#

go away

indigo arrow
#

I'm having a weird issue where my bullet prefab is colliding with the environment, but these collisions aren't being detected by its script:

using System.Collections.Generic;
using UnityEngine;

public class EnemyBullet : MonoBehaviour
{
    float bulletForce = 12f;
    float bulletLife = 2f;
    AudioSource source;
    public AudioClip bulletCastSound;
    public AudioClip bulletImpactSound; 
    public int bulletDamage = 1;
    public float bulletKnockback = 7;
    float currentBulletLife;
    Rigidbody2D bulletRb;
    void Start()
    {
        bulletRb = GetComponent<Rigidbody2D>();
        source = GameObject.FindWithTag("GameManager").GetComponent<AudioSource>();
        source.PlayOneShot(bulletCastSound);
        currentBulletLife = bulletLife;

        bulletRb.AddForce(transform.up * bulletForce, ForceMode2D.Impulse);
    }

    void Update()
    {
        if(currentBulletLife <= 0)
            Destroy(gameObject);
        else
            currentBulletLife -= Time.deltaTime;
    }

    void OnColliderEnter2D(Collision2D other)
    {
        print("Enemy bullet hit");
        source.PlayOneShot(bulletImpactSound);

        bulletRb.velocity = Vector2.zero;
        LeanTween.scale(gameObject, new Vector3(0.001f, 0.001f, 0.001f), .5f)
        .setEase(LeanTweenType.easeOutExpo)
        .setOnComplete(() => {
            Destroy(gameObject);
        });
    }
}```
#

am i missing something obvious

robust dome
#

@indigo arrow probably the collision is taking place and it is too short to be detected means the bullet might be traveling too fast

#

i also see an error in your code

indigo arrow
robust dome
#

void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("OnCollisionEnter2D");
}

#

it should look like this

#

you should always let intellisense do the work for you to prevent such mistakes, it seems like you typed it manually

indigo arrow
# robust dome void OnCollisionEnter2D(Collision2D col) { Debug.Log("OnCollisionEnt...

but i have this on my player script:

    {
        if(col.gameObject.CompareTag("Enemy") && currentISecs <= 0)
            TakeDamage(col.gameObject.GetComponent<Enemy>().enemyDamage, col.gameObject.GetComponent<Enemy>().enemyKnockback, col.transform, false);
        else if(col.gameObject.CompareTag("EnemyBullet") && currentISecs <= 0)
            TakeDamage(col.gameObject.GetComponent<EnemyBullet>().bulletDamage, col.gameObject.GetComponent<EnemyBullet>().bulletKnockback, col.transform, true);
    }```
#

and that works fine

robust dome
#

yeah but look at the difference

#

you have OnColliderEnter not OnCollisionEnter

indigo arrow
#

my bad

robust dome
#

intellisense use it ;D

indigo arrow
#

i misread yours as (Collider2D) rather than (Collision2D)

#

thought that was the difference

indigo arrow
#

works now

topaz ocean
#

how do I access the colors in project preferences from script

leaden ice
#

like the editor theme colors?

topaz ocean
#

Im specifically going for axis colors

leaden ice
#

I've never tested if that actually changes with the editor settings

#

but I imagine it does?

topaz ocean
#

seems to work, im not trying to change them, just use them for drawing debug stuff

muted vigil
#

How do people structure flexible power ups?
My approach was for each thing to have a list of power ups where they can "hook" into points where systems interact. Below I have a couple spots set up so for when anything would take damage or deal damage it would loop over its power ups and pass the data for each one. Is this how people normally handle it?

public class Powerup: ScriptableObject
{
    protected PowerupAble PowerupAble;
    public Powerup(PowerupAble powerupAble)
    {
        PowerupAble = powerupAble;
    }
    
    public virtual  void Setup()
    {
        
    }

    // Update is called once per frame
    public virtual void Tick(float timestep)
    {
                
    }

    public virtual void OnDamageTaken(Damage damage)
    {

    }

    public virtual void OnDamageDealt(Damage damage) { 
    
    }

    public virtual void OnMovement(float speed)
    {

    }
}
rigid island
muted vigil
#

updated above. so that would be a scriptable object where each power up would inherit from, so would the solution of providing a bunch of "hooks" where the power up can listen for when it is applicable seem reasonable?

west lotus
pure cliff
muted vigil
#

so say the player has a damage power up to do 15% more damage. When the player's weapon hits before the damage gets applied, that damage would be passed to each function in a list and the final damage returned would actually be used and then that damage would be ran through the powerups OnDamageTaken for what is being damaged.

pure cliff
#
  1. Do these powerups need to "Stack" with themselves, IE can you have for some buffs 3 copies ("Stacks") of the same buff?
  2. Do they have expirations, and do you want/need to track the expirations individually
  3. If you answered yes to both above, do you also need to track the expirations individually for each individual stack of the same buff?
leaden ice
muted vigil
# pure cliff 1. Do these powerups need to "Stack" with themselves, IE can you have for some b...

Not originally planned. The idea was random where they could "stack" and I was just going to treat it as having 3 instance say of the same power up. Yeah my idea for anything expiration based would be on the Tick function would let it do its countdown there and self remove.

How would you handle more complex scenarios? Say Like on successive hits you get a stacking modifier for that buff but if you miss it drops off or say you get a power up that has a modifier for how far you are from the target you hit?

muted vigil
pure cliff
# muted vigil Not originally planned. The idea was random where they could "stack" and I was j...

each of your "types" of distinct buffs needs to have its own unique identifier, Guid or whatever.

I would likely have a some form of "subscribe" and "unsubscribe" method on something I would call a BuffContext or... something like that. When the player's stats change so that they gain or lose the capability of a buff, I would call up that respective Buffcontext and fire off its subscribe or unsubscribe.

So for example lets say you can get FooStacks from the FooAbility. When the player equips the item that grants them the FooAbility, it would have a list of associated BuffContexts that need to fire off their Subscribe methods, because they now have stuff they need to watch for.

So your FooStackContext would add a subscription to listen for, specifically, the "Attacked" event, and it would get the attack data, and it would then decide if it adds new FooStacks, or remove em all based on your example.

When you equip the item you fire off FooStackContext.Subscribe method, and when you unequip you fire off the FooStackContext.Unsubscribe

The buffs themselves would likely just be a Dictionary<Guid, PriorityQueue<float>> sorted such that the "first" item to be dequeued is the one with the lowest duration.

And on your "ticks" you just decrement all the values in the queue, and if they are still a positive value you re-add em to the queue for next tick.

muted vigil
#

ah I see so youre saying change it from the Powerup having all of these virtual functions and just slim it down so that the Powerup gets a context of all the things it can interact with weapons,health, movement etc and then subscribe to events and do something like this https://stackoverflow.com/questions/1446256/pass-a-return-value-back-through-an-eventhandler to let whatever emitted the event get the final result of modifers and then do whatever. Yeah that definitely seems more flexible.

swift falcon
#

I'm trying to modify a Texture2D's Multi-Sprites to contain all the sprites parsed by an Adobe Animate XML parser also written by me, however I'm currently experiencing the issue that my code places the SpriteRects inverted vertically (as can be seen in the attached photo).

I have tried different versions of subtractions and additions to attempt to fix it, but the issue still persists, all other combinations making it worse.

This is my current code that causes the attached issue: https://hastebin.com/share/sonokalubi.cs, any help is appreciated!

mighty yew
#

Creating a combat system, and a big part of it is the modularity of actions in the game. For example you can replace your attack 1 with a different attack2 in order to adapt to the situation. To code attacks I have an "attack" class that i plan on being the parent to all the other attacks. Issue is, in the child attacks I cant declare values to variables that have changed. Ie:

public class Attack{
  public int damage:
}
public class DiffAttack : Attack{
  damage = 3 //doesnt work
}
#

not sure how to fix this

#

But also, is this even the way i should be going at it? Is there a better way to do this?

knotty sun
#
public class DiffAttack : Attack{
public DiffAttack() {
  damage = 3; // will work
}
}

will work

mighty yew
#

cool! thanks! (how did you color the code in c#)

knotty sun
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mighty yew
#

also cool!

runic cave
#

I'm trying to get a UI (using canvas) to draw on the screen where the mouse is. Does anyone happen to have a link to something that explains how to do this? Google doesn't seem to understand what I'm trying to search for (keeps giving me tuts on moving things with UI not moving the UI itself)

leaden ice
runic cave
#

no, trying to make a popup menu that appears at the mouse position when I click on an object

#

I'm making some progress but this UI stuff is so confusing

leaden ice
#

basically:

Vector3 mousePos = myCam.ScreenToWorldPoint(Input.mousePosition);
tooltip.transform.position = mousePos;```
#

and again - this only works in Screen Space - Camera

sterile gate
#

Im attempting to get the colors in a sprite to check if the image is completly transparent. Though every single image is returning the colors as full black and reading as transparent. Ive read the documents and since my texture is created at runtime is should automatically be readable, why are all the pixels returning as black?

//CREATE SPRITE
  Sprite slicedSprite = Sprite.Create(texture, new Rect(xPos, yPos, 16, 16), new Vector2(0.5f, 0.5f), 100.0f);

//RETURNS TRUE ALWAYS?
if(!IsTransparent(slicedSprite.texture)) { }

//BOOLEAN, EVERYTHING IN INSPECTOR IS BLACK
public List<Color> loadedColors = new List<Color>();
bool IsTransparent(Texture2D tex)
{
    Color[] pixels = tex.GetPixels(0);
    foreach(Color co in pixels)
    {
        loadedColors.Add(co);
        if (co.a == 0)
        {
            print("isAlpha");
            return true;
        }
    }

    return false;
}
leaden ice
#

you're also adding every pixel to that list which is going to grow quite large 😮

sterile gate
#

Yes, I dont want any transparent sprites, but even the sprites that should not return transparent are returning alpha true. Actually it only loads 210 into the list, which is it look like it actually stops reading pixels after 210. There is no error or clear list called, why is it just stopping? o_O

leaden ice
#

is that what you want?

#

It will stop when it gets to return true; ofc

sterile gate
#

Yes im iterating through a list. So it seems like its only checking one tile then stopping.. and not running the isTransparent function anymore

  for (int i = 0; i <= 69; i++)
        {
            if (curColumn >= 5)
            {
                xPos = 64;
                yPos -= 16;
                curColumn = 0;
            }

            //CREATE SPRITE
            Sprite slicedSprite = Sprite.Create(texture, new Rect(xPos, yPos, 16, 16), new Vector2(0.5f, 0.5f), 100.0f);

            if (isAnimated && !IsTransparent(slicedSprite.texture) || isVariant && !IsTransparent(slicedSprite.texture) || !isAnimated && !isVariant)
            {
                //ADD TO LIST (WE SAVE AND LOAD DATA BASED ON THIS LIST)
                gameMaster.mapSprites.Add(slicedSprite);
                textureSprites.Add(slicedSprite);

                //SPAWN THE BUTTON
                //IF WE ARE ANIMATED OR VARIANT, ONLY SPAWN THE BUTTON ON THE FIRST SPRITE, SAVE THE REST TO THE LIST
                if (isAnimated && totalpos == 0 || isVariant && totalpos == 0 || !isAnimated && !isVariant)
                {
                    baseSprite = slicedSprite;
                    GameObject spriteButton = Instantiate(buttonPrefab, containerPrefab);
                    spriteButton.transform.GetChild(0).GetComponent<Image>().sprite = slicedSprite;
                    spriteButton.gameObject.SetActive(true);
                    spriteButton.gameObject.name = xPos + "," + yPos;
                }
            }
            //MOVE TO THE NEXT TILE BUTTON
            xPos -= 16;
            ++curColumn;
            ++totalpos;
        }

This is slicing a texture, iterating through the tiles. and im checking if any are transparent, not to add them to a list Im using

leaden ice
#

I don't see how that part is really relevant

#

also

#

you are anaylizing the entire texture every time

#

not just the individual sprite

sterile gate
#

ah. does "sprite.texture" reference the entire original texture, and not make a texture reference based on the sprite size..?

#

I think that makes sense as to whats going on if thats whats happening. Im not sure how to grab the colors inside of my sliced sprite so I can check if its just transparent or not

leaden ice
#

I mean you even calculated the pixel range already: Sprite slicedSprite = Sprite.Create(texture, new Rect(xPos, yPos, 16, 16), new Vector2(0.5f, 0.5f), 100.0f);

#

Honestly the most efficient thing though will be to get the color array outside this whole loop one time and just reuse it over and over

#

checking the section you want each time

#

which is not the same as all transparent

sterile gate
#

BacBacBearDoh Oh wow that makes much more sense. Thank you!

blissful dust
#

My game is meant to have a pilotable airship with physics (I dont want it clipping through the ground) that the player can walk around on but also control. My current solution is to have a CharacterController on my player handling movement, and a Rigidbody on my airship that I add forces and torque to in order to control it. I also set up a trigger box collider to detect if the player is on top of the ship, in which case it makes the player a child of the ship to maintain it's speed. However, because the player and the ship both technically use a rigidbody, the ship (which ignores gravity) is pushed down by the player (who is being forced down by gravity). Is there a good way of making the ship ignore the player's effect on it? I thought about increasing the mass of the ship to an incredibly high number so the player doesn't affect it, but this sames janky, and I saw something about using a physics scene to calculate the player position, but I've never done that and I'm hesitant to implement a complex solution when it might not be needed.

Also, I've found it's not a great idea to ask for a solution for something when there could be an entirely different approach that works better, so if anything I said above could be changed to simplify the entire process, that would be great

spring creek
#

Or set a negating velocity of y +9.8

blissful dust
nocturne grove
#

While not moving*

blissful dust
spring creek
#

Kinematic rigidbodies respond to collisions

blissful dust
#

once it starts moving if I set it to non-kinematic (enabling physics) it'll immediately start to drop again tho right?

nocturne grove
#

It won't respond like it's being pushed

spring creek
blissful dust
blissful dust
nocturne grove
#

The issue is the player character pushing the ship. The ship is in zero gravity, but the player pushes the ship

#

The issue here is the player pushing the ship

spring creek
spring creek
nocturne grove
#

The ship won't be pushed around while Kinematic

#

Which could be an issue if you want asteroids to do that

blissful dust
#

it gets kinda paradoxical though, if I were to slam the ship into a wall and it is kinematic, would the ship just go straight through the wall?

nocturne grove
#

However, if you want to do kinematic, you can make special collision events for this cae

blissful dust
#

but if I make it non-kinematic it'll respond to my player

spring creek
blissful dust
#

well yeah my wall would probably just be another kinematic rigidbody, its not gonna move or anything

spring creek
blissful dust
#

gotcha, so I guess I could just like calculate how hard it should bounce off the wall myself and apply that to the rigidbody

nocturne grove
#

Exactly

blissful dust
#

okay cool, I'll try that out and see if I still need any help, really appreciate it guys

nocturne grove
#

np

spring creek
#

I dunno if that would be worthwhile at all lol

blissful dust
#

seems janky though, I'll try manually calculating it first

wintry crescent
#

Why does this line
if (!gameObject)
throws an error

Your script should either check if it is null or you should not destroy the object.```
isn't this line supposed to check if it's null or not?
leaden ice
#

but really you should just - not call whatever function this is if this thing is destroyed

wintry crescent
#

it removes the call from the event that called it inside that if

silk niche
#

i know i can just make it move along the spline, but don't know how to access to other stuff

wintry crescent
foggy pasture
#

is anyone experienced with parrelsync? i'm encountering an issue where scriptableobjects don't match the parent project, often in strange and random ways

leaden ice
foggy pasture
#

one sec, let me find an example and check

#

it's happening primarily with a field that i have an attribute attached to

leaden ice
#

what attribute?

foggy pasture
#

[CustomPropertyDrawer(typeof(ScriptableObjectIdAttribute))]
public class ScriptableObjectIdDrawer : PropertyDrawer {
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
        GUI.enabled = false;
        if (!ClonesManager.IsClone() && (string.IsNullOrEmpty(property.stringValue) || int.TryParse(property.stringValue, out int number))) {
            property.stringValue = Guid.NewGuid().ToString();
        }
        EditorGUI.PropertyField(position, property, label, true);
        GUI.enabled = true;
    }
}
#

it's just to generate unique guids for scriptableobjects

#

i assume i need to serialize this field somehow?

leaden ice
#

is the id field not serialized?

#

I can't imagine it's much use without being serialized

foggy pasture
#

it should be, it's visible in the inspector

leaden ice
#

It's visible in the inspector because you literally have a property drawer drawing it
EditorGUI.PropertyField(position, property, label, true);

#

is it serialized?

foggy pasture
#

i'm unsure of how to check outside of inspector visibility

leaden ice
foggy pasture
#

i assumed it was because of the propertyfield docs describing what it creates as a serialized property

leaden ice
#

and it needs to be of a serializable type

foggy pasture
#

it is public, but let me try it w/ serializefield

leaden ice
#

public is fine

foggy pasture
#

ah ok

#

so it probably isn't serialization causing the issue in that case

manic maple
#

controller.Move(move * speed * Time.deltaTime);

    if(Input.GetButtonDown("Jump") && isGrounded)
    {
        velocity.y = Mathf.Sqrt(jump * -2f * gravity);
    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);
#

can you reference a charactercontroller.move twice? how does that work?

somber nacelle
#

it moves the CharacterController twice in that frame

leaden ice
lean sail
somber nacelle
#

it's pretty typical to see this in tutorials, and even on the unity docs. it's technically better to do your move all in one call though

manic maple
leaden ice
astral sky
#

Are there any special or unique rules for instancing gameobjects in DoTS? Not sure If I should ask it here or make a thread in the dots forum, but I thought it was simple enough to be posted here
Is it just the usual Object.Instance(prefab)?

leaden ice
astral sky
#

Well, yeah but since I have authoring components, I dunno how that's handled if instanced right there at runtime, considering that has the baker... steps
Baking only happens in the Editor and never in-game

#

I'm used to having Scriptable Objects (as spawncards) which hold prefabs, I started with dots past week and I'm pretty much rethinking how I gotta do stuff and the rules (like can I mix a gameobject that has a authoring component (ECS) and usual monobehaviors? that's what cameras are right now, as there's no ECS version of cameras?)

#

So I don't know how much can it be dots, how much it has to be dots, if I can mix and match

#

etc

leaden ice
foggy pasture
#

you just need to add ```

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
#

after the guid changes

#

to sync the change to parrelsync

sonic vault
#

how do I get a true or false if a button is being held or pressed with the new input sytem and invoke unity events?

leaden ice
sonic vault
#

lemme try that real quick

#

ok that did not really work, can you tell me how I send my code to you?

leaden ice
#

and explain in what way it didn't work

sonic vault
#

I have a bool called is firingcontisully but the bool does not change

leaden ice
sonic vault
#

It set it as false in the start and it remains as false even when im touching the the button

leaden ice
#

Also you never shared:

show how you set up the input action

sonic vault
#

isFiringContinusly is a public

leaden ice
sonic vault
#

yep

leaden ice
#

so is the code actually running?

#

Is your thing printing?

leaden ice
sonic vault
#

I have it set up as an event (the onFire is the is the one where focusing on)

leaden ice
#

The "Fire" action

leaden ice
sonic vault
#

the input dected is printing

sonic vault
leaden ice
sonic vault
#

ok on it

leaden ice
#

also it's not going to "continuously" do anything really

#

this will only be called when you actually press or release the button

sonic vault
#

by golly gosh that worked

#

but why though?

leaden ice
#

you probably want something like:

void Update() {
  if (isFiring) DoSOmething();
}

void OnFire(InputAction.CallbackContext ctx) {
  if (ctx.started) isFiring = true;
  else if (ctx.canceled) isFiring = false;
}```
leaden ice
#

don't do it if you don't know what you're doing

sonic vault
#

thank you so much man you are a real one

blissful dust
spring creek
blissful dust
#

yeah, I just tried putting a box collider on the ship though and it didn't seem to make a difference

copper yew
#

Heyyy

spring creek
#

Does the OTHER thing its colliding with have a collider? Both need a collider and one needs a rigidbody. Pretty sure it has to be the same object with rb and collider too, but not sure

copper yew
#

Holy moly i can ask my questions after long time

blissful dust
#

yeah, the thing it's colliding with actually has a kinematic rigidbody and a collider on it

spring creek
blissful dust
#

nope, haven't messed with it at all

#

lemme send a screenshot or two just to make sure im not completely overlooking something

spring creek
#

I would put a debug in the oncollisionenter, not behind an if or anything

#

Just to help with checking

blissful dust
spring creek
#

Hmm ok, and the debug never fires... weird

blissful dust
#

yup, not really sure why it wouldn't

spring creek
blissful dust
#

I just created a cube with only a box collider and rigidbody and if its non kinematic it works

blissful dust
#

guess im back to square one

spring creek
#

Yeah sorry!

blissful dust
#

nah its all good, it was a step in the right direction I think

quartz folio
wispy raptor
#

which unity version should i use if i wanna use .net 7 in unity?

#

currently i am using unity 2022.3.3f1, it uses .net 6, i wanna use .net7

#

because .net7 has a lot of new features

#

that are very useful

#

also some performance improvements

late lion
#

They are in the progress of switching over from Mono to CoreCLR, which is what .NET 6 and 7 are based on. That will take a while.

wispy raptor
#

aaa okz

#

thank you

spring creek
#

Yeah I was being dumb and thinking c# version lol. But this is the status for .net

brave cove
#

Hello :>

I'm encountering a rather problematic issue and I wonder if I could get some help in here ^^' I couldn't find anything relevant on internet
So I have this Coroutine which I use to transition between multiple user-selected background music themes (see first attachment)
I call it once upon starting the game, and then transition smoothly when switching themes like so (see second attachment)

The problem is the following: I can only select each theme once, after which it doesn't switch anymore. I think it has to do with how coroutines can only run once (or something), and I've been stuck on this issue :>

brave cove
leaden ice
leaden ice
brave cove
brave cove
#

problem is I can only select each theme once

leaden ice
#

so once they play, they've played

brave cove
#

they are TwT

leaden ice
brave cove
#

I'll do so then

#

oh also

#

last time I checked the audiosource volume while switching

#

it was like, going back and forth

#

so I think it calls both FadeSound in and out, or something

leaden ice
brave cove
#

there's only one tho

leaden ice
brave cove
#

wait, is it maybe that you can't start the same coroutine simultaneously with different parameters?

leaden ice
#

there's no limits on calling the coroutine

brave cove
#

ah

brave cove
leaden ice
brave cove
#

once everytime I switch dropdown otpion

leaden ice
#

how are you calling it

#

can you show that code

brave cove
#

here

leaden ice
#

Maybe add a log to it and make sure it's not being called more often than expected

brave cove
#

aight

#

so I:

  • started the game (Starglitter Sky was preselected)
  • switched to Wings from Beyond
  • switch to Ode to Spring
  • switch back to Wings from Beyond
#

it seems the FadeSound in isn't called

#

here are the logds

#
  • 1 when calling SetTheme
dusk apex
#

Relative to the logs.

brave cove
#

nvm, so it does call it x) I didn't see it cuz of the collapse

#

when I look at the volumes of each audiosource, whenever I go back to Wings from Beyond, it's volume isn't actually going up

#

idk what causes this

#

I know what the problem is, it's this line

is there a way to save the volume outside the coroutine? because sound is a parameter of that coroutine so idk if that's possible

leaden ice
#

but yeah this makes sense, once it goes to 0 it will never come back up

#

because 0 * anything is 0

brave cove
leaden ice
#

you'll want to save the "max volume" variable somewhere

#

and never change that

#

so sound.voume = maxVolume * i; should be in the loop

brave cove
#

hmm I dunno how it couold be done tho

leaden ice
brave cove
#

I stuck to this for now, cuz of all em have 0.5 volume

leaden ice
#

also volume is almost definitely not 0.5

#

nvm audiosource volume is 0-1

#

so that's probably ok

brave cove
#

well, how can you set maxVolume once as a variable outside the coroutine?

leaden ice
#

or even const float maxVolume = 1;

brave cove
#

yeah, but shouldn't it depend on the sound.volume in some way?

brave cove
#

well what if one theme is slightly louder than the other, meaning i'd have to set it to 0.4, for instance

leaden ice
#
Dictionary<AudioSource, float> maxVolumes = new();

void Awake() {
  foreach (AudioSource source in themes.Keys) {
    maxVolumes[source] = source.volume;
  }
}```
#

and then in the coroutine:

float maxVolume = maxVolumes[sound];```
brave cove
#

oh wow

#

I didn't think of that actually

#

I'll try it, thanks! :>

green radish
#

how might someone create an array of variables, if that makes sense? for instance having each member of the array contain one int and one string variable

unreal sparrow
#

Can someone help me with this code? Basicly I am trying to get my eyelid blendshape value to reach 100 as my eye y rotation looks up and also for the value to decrease as it start to rotate down. I got the blendshape to be affected as the eye looks up but the value instantly shoots up to 100. I've been trying to smooth it out with lerp. Also I need it to decrease as starts to make it way down the y rotation value.

wispy raptor
#

when you code a customeditor, is there a method to show the default inspector for an specific type? for example if i have a generic type, i would like to show a text field if it is a string, a numeric field if it is a int or float, etc... or must i use just a kind of switch?

wispy raptor
#

thanks

lean sail
green radish
#

I intend to use this for storing the name and number of frames for animation cycles

#

I would get the name and number from the variable and feed it into the custom animator I'm building

brave cove
#

dunno much tho

night harness
#

Hey friends. Not a super specific question but more of a general coding practice vibe check. Theres been once or twice where I have a state machine that I want to fire off events based on when the state changes, It feels messy to have a delegate or unityevent per enum state but is that just my head being silly or is there an actual better way to do this

#

I thought about a UnityEvent that passes through the new state but i figure having a bunch of events is better than calling a bunch of irrelevent functions just to fail a comparison with that state

mighty yew
#

I have a class called Attack, and I want to have a bunch of objects (lets say 20) that all inherit from this class. The class contains 2 ints, and an "animationClip". Is there a way to effeciently create these "attacks" and be able to reference them?

night harness
#

Kinda sounds like you might want to look into scriptableobjects?

#

Depends on your usecase

#

I'm guessing those 2 ints are attack stats open for designers to tweak?

mighty yew
#

Yeah they are, ill look into scriptableobjects

#

not really sure if this is the best way to do it ngl

spring creek
#

You could have a field for an attack scriptable object and just have different SOs added in and out to the ONE attack class, like Batby was saying

Or similarly, use a serializable struct and have prefabs with the different values

sonic oyster
#

Hello friends, I'm experiencing an issue related to JSON parsing. Could you please help?

spring creek
green radish
#

is there any way to stop this weird Editor UI behavior? This is an array of my custom class that stores cycleName(string) and cycleLength(int) variables, this overlapping only happens on Element 0, on every other Element the array UI expands to make room

sonic oyster
spring creek
spring creek
green radish
#

saves chat space and people can get straight to answering

sonic oyster
#

I've written a login code and I'm accessing this code from PHP. However, whenever I try to execute the login process when status = true, JsonUtility.from doesn't allow it and gives an error. I've also included its screenshot.

sonic oyster
pure cliff
night harness
# mighty yew not really sure if this is the best way to do it ngl

ScriptableObjects for stuff like this can feel abit redundant and bloaty but it's really nice to have them as disconnected files like that. What you can do is have your Attack SO's store those three values and then when whatever ends up using them, they grab those values off the scriptableobjects (on update, on a custom loading function etc.)

green radish
#

the old UI doesnt have it

spring creek
#

Oh really? 😂 sad but also a tiny bit funny.

Sometimes when we move forward we stumble I guess

green radish
#

probably something to do with the elements being reorderable being broken, since turning that off is what fixes it

prime sinew
#

it was fixed in a later Unity version, but i forget which

green radish
#

I'm a bit afraid to update my project to a new version since that has an alarmingly consistent pattern of breaking my projects beyond repair

prime sinew
#

you can try making a backup first 🤞

night harness
#

Hey friends. Not a super specific question but more of a general coding practice vibe check. Theres been once or twice where I have a state machine that I want to fire off events based on when the state changes, It feels messy to have a delegate or unityevent per enum state but is that just my head being silly or is there an actual better way to do this
I thought about a UnityEvent that passes through the new state but i figure having a bunch of events is better than calling a bunch of irrelevent functions just to fail a comparison with that state

#

lmao ty for that

green radish
prime sinew
#

dear god, it was around for that long

#

2020 to 2021 might be a big jump. all the best if you decide to upgrade your project

green radish
#

it was fixed in 2022

prime sinew
#

oh

#

oops, i forget editor versions dont reflect year of release always

green radish
#

I started my project in 2021 and out of fear of file corruption chose not to update to the next version

prime sinew
#

well, can always make a backup and experiment on upgrading that. that's all

green radish
#

true

hidden flicker
#

Currently having Schrodinger's bug

pure cliff
hidden flicker
#

...ok let me finish lmao

#

When my player is selected in the inspector, they move normally. But when they aren't, they move much faster than they should

pure cliff
#

Oh fascinating

#

What's your code for player movement look like?

hidden flicker
#

Before you see it

#

I know it's messy

#

Please forgive me

pure cliff
#

I'd maybe think it's perhaps your inputs are doubled somehow or something

hidden flicker
devout solstice
#

So i forgot to write my script using fixed update right, and it’s already basically finished, so i switched the update to fixed update and when i press tab to open the gui, i have to push tab multiple times to get it to open i don’t have any clue why that would be

leaden ice
#

Or that happens

devout solstice
#

oh shit

#

ok

leaden ice
#

Input processing goes in update

devout solstice
#

gotcha thank you

hidden flicker
#

Anyone got help for the... confusion

devout solstice
#

this will work fine right?

prime sinew
blissful dune
#

hello to all, anyone know how can read a json and convert into a object list?

leaden ice
#

Basically any json parsing library

blissful dune
#

i try to use newtonsoft but cant add into my proyect

leaden ice
blissful dune
#

ty

#

lovely

#

JsonUtility only parse a single object...

devout solstice
#

ive forgotten how while loops work

#

i know youve gotta return or else itll crash unity

#

but thats not working right

leaden ice
#

No you need to just not make the loop infinite

devout solstice
#

oh

leaden ice
#

It will run untill the condition is false

devout solstice
#

i want it to run as long as a certain button is pressed

leaden ice
devout solstice
leaden ice
#

You want Update

#

Not a loop

devout solstice
#

oh

leaden ice
devout solstice
#

it would when i let go of the key

leaden ice
#

Input is only processed once per frame

#

At the begining of the frame

devout solstice
#

if i use a if statement it still only runs once on each key press

leaden ice
devout solstice
#

maybe i was using the wrong input thing

leaden ice
#

Yes

#

You were

devout solstice
#

ah now it works

nova magnet
hidden flicker
edgy ether
#

So i have a texuture that i'm trying to change the settings to while in editor. just some basic settings like , disabling mipmaps, changing mesh type and making it readable.

problem is, i can't simply change it through the inspector because the duplicate texture gets created in ram (i believe) leaving me unable to change the settings.
so i want to change these settings using code while in the editor. how would ii do this?

worn stirrup
#

Uuuu what's the best way to measure the physical length of a sprite I have in-scene

#

wait that sounds googleable

#

oh prolly rect

thorny spindle
#

Are there any good Unity Open Source game/projects out there?

worn stirrup
#

This has somehow been such a long rabbit hole of such bad code 😅 I'm trying to set up a 2D chain-link spawning system, but trying to figure out how tall a link is to precisely offset the new one is proving wildly difficult

#

aaand I just got it lol

#

time to fis physics for 2 hours

spark flower
#

can someone help me out

#

why am i getting this error

prime sinew
spark flower
#

from the print it seems _items is not null

#

like it is length of 1

prime sinew
#

Since you initialized _items in line 43, it should be items[j] that's null

#

Yeah

#

Check _items[j] then

spark flower
#

and j is 0 basicly

prime sinew
#

Oh _item might be null

#

I forgot to see the right side of =

spark flower
#

from the print its seen that its not

prime sinew
#

Is the error message recent

spark flower
#

thius is Item

#

what do you mean recent

prime sinew
#

Like the line number hasn't changed by you changing the code

spark flower
#

nothing has changed

#

it is as i have it rn

prime sinew
#

Try debugging items[j] and _item

#

Then show the log

#

Just to confirm

spark flower
#

if i just print _item, it just shows Item, so i print item.name and it shows correctly

quartz folio
#

🌈 use the debugger

spark flower
#

ok

#

it seems its null

#

which doesnt make sense to me

#

any ideas?

quartz folio
#

Use the debugger and you'll see exactly what's null and how you might not be assigning it

#

because you can just step over the code and see it execute, seeing the values it contains, etc

spark flower
#

where is this debugger

spark flower
#

and really thats the whole code

#

dont you have an idea why its null

lean sail
#

no one wants to 🥣, learn how to debug 😊

spark flower
#

its just an array extending function, a simple answer wuld be best

quartz folio
#

You never assign it a value, so it is null.

#

You could see this if you learnt to use the debugger, and then because you knew how to use it you would never have any more questions

spark flower
#

well how do i assign it a value

quartz folio
#

new

spark flower
#

Item[] _items = new Item[assets.Length + 1];

#

and what does this do then

#

doesnt it give it default values

quartz folio
#

No

#

Classes are null by default.

spark flower
#

i see

quartz folio
#

Again, please learn the debugger, it takes 1/2hr and then you're set for life

spark flower
#

well the problem was i didnt know i have to give new to every single entry,

#

the debugger wuld tell me its null and ill still be confused as to why

#

the debugger is not the right option in this case

lean sail
#

Sounds like someone whos never used the debugger

quartz folio
#

You would have seen that it was null in the array without every having to put down a single print statement, you would have seen you writing your new values into the array, and then you would have inferred you needed to assign something to that index

#

If you are using print statements for debugging you should be using the debugger instead

spark flower
#

i wuldnt have guessed that i have to make a new class() for every entry

quartz folio
#

You don't, you only have to make it for the one that is null

spring patio
#

Anyone have an idea how to disable Button GameObject in Script? SetActive(false) doesn't seem to work.

spark flower
#

well theyr all null since its a new array

quartz folio
#

but you're writing elements into it, so those will not be null

prime sinew
quartz folio
spark flower
#

and id bet ill get an error for the loop if i dont put new class() for every iteration

quartz folio
spark flower
quartz folio
#

Depends whether you want the arrays referencing the same objects or not

spring patio
quartz folio
quartz folio
spring patio
#

ooooo

#

tysm 😄

spark flower
spring patio
#

forgot about the gameObject part :/

spark flower
quartz folio
spark flower
#

i know

quartz folio
#

So, do you want the new array to reference the same objects as the original one?

spark flower
#

yes

quartz folio
#

Then assign them directly instead of assigning each member one by one

#

Or use Array.Copy or something

spark flower
#

well how do i resize it after that

quartz folio
#

Don't do this inner member assignment stuff, instead do _items[i] = assets[i];, or use Array.Copy to replace the whole loop

#

Or just use a list and don't do any of this

spark flower
#

im alredy doing that

#

just copying the array wont make it a new size

#

and i need it a new size

#

like i sayd the function is just an array resizing function

#

i dont think theres a way without iterating thru everything

quartz folio
#

I can't get through to you, so I'm out, someone else can help, but I'd advise not bothering as this is absurd

spark flower
#

well your not making much sense to me

quartz folio
#

I've spent far too long talking to you, after you refused to use the debugger and have shown no indication you ever plan to I should have stopped

spark flower
#

the debugger is not nececery here, the whole code in question is in one function, and is basic

swift falcon
#
    [SerializeField]Vector2 HullDimensions
    {
        set
        {
            GetComponent<BoxCollider2D>().size = value;
            GetComponent<SpriteRenderer>().size = value;
        }
    }

is there any way to do something like this so that i can change both of these values through the inspector ?

limber herald
green radish
#

is there any way to modify Unity's Tilemap system to allow per-tile data storage?

swift falcon
green radish
spark flower
quartz folio
# swift falcon mega unfort 😔 ✊

You would have to make a custom editor or drawer that found those properties and drew them using PropertyFields, but there's no straight forward way

limber herald
# spark flower what do i need to use for Array?

The Array class is a static class from the System namespace, so you don't have to replace it with anything really. And if you get an error saying "Array" not found, just make sure you have using System; at the top of your code

spark flower
#
        Array.Resize(ref assets, assets.Length + 1);
        assets[assets.Length - 1] = _item;```
#

so this basicly

quartz folio
#

and with _items[^1] = newValue we can further reduce the hellcode to nothing and it will disappear from existence

spark flower
#

assets[^1] = _item; so just this?

spark flower
dusk apex
simple egret
#

Maybe they're on an older version where indices aren't supported

#

But who knows, without the error message

lean sail
#

my moneys on they didnt assign _item to be a thing

scarlet viper
#

Changing Transform on a Prefab instance (Placeholder for referenced MonoBehaviour in Prefab instance (1)) is not allowed.

#

cant compile i have this error

#

its something with TEXTmeshpro

winged mortar
dusk apex
quartz folio
edgy pumice
#

Hello, everyone.
I was wondering, whether I am on the right track with this one or whether there are better ways to do it.

I'd like to instantiate a prefab of certain dimensions at distance, corrected by raycast hit on specified layers and collision of said prefab.

My thought is to check for raycasthit2d . point - ( bounds.size.y / 2 corrected by direction of the prefab ) and... decrease the checks by increments until I can fit the bounds without colliding with anything.
But this seems tedious and unintuitive. Any thoughts?

spark flower
dusk apex
#

So a length of zero