#archived-code-general
1 messages · Page 172 of 1
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
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
alr ty
You can represent any negative angle as positive🤷♂️
I nabbed a positive clamper to help with this, but I'm still not understanding how to get what I'm looking for...
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?
the randomized spawner make 1000 instanses in a random patern in my world
btw @night harness I have a write up here you can check out that walks you through my architecture I like to use for setting up a decoupled GameState "single source of truth" system for Unity, its a quick small tutorial that demos how you can use Zenject + PropertyWatcherBase to make life easy
https://blog.technically.fun/post/unity/building-a-gamestate-with-zenject-in-unity/
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:
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
either way u dont need a second layer spawner either
why not?
if randomized spawner make 1000 random objects spawned,
just spawn the coin instead
well i want when the coin is collecnted it to respawn after a certian amt of time
-
make an array of gameobject prefab
-
use random.range to pick random object from the array
-
spawn out the object
one spawner is enough
You're doing lerping wrong. Check the documentation on the third parameter.
im thinking since the randomized spawner works by if amt of spawned object is less then 1000 it keeps spawning, to theoretically if i delete one coin it will spawn another somewere else
Sounds like a question for #💻┃code-beginner
I'm not lerping wrong at all, that's a technique to create a gradual interpolation using Lerp
it will work, i just think adding up a second layer of spawner with no specific reason is quite pointless
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.
- You are using Lerp wrong
- Modifying
sharedMaterialwouldn't do anything when there ismaterialor overriden with particle's property
i will work on it lol
well idk if what i just came up with will work, and i added the second layer cuz i already created the first coin spawner so i just added on to that
I've tried both, and I also don't see how I am using Lerp wrong.
There's smoothdamp and other methods for gradual interpolation. You are using lerp wrong. It's never gonna reach the target value.
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
- a spawner that spawns coins in RANDOM places
- this spawner will spawn another coin once the coin is collected
right?
Lerping is.
Lerp(a, b, deltaTime) :p
ye something like that. now i just gota imploment it
or wait no derp
Your lerp is not framerate independent, and not predictable
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
Lerp aside, it's not the root of my problem
Generally you'd use particle system's option (color over time)
Or modify particle itself (via GetParticles/SetParticles)
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?
I'm basically trying to fade out a group of existing particles before I disable the parent game object
first one seems like what i have rn. but its a bit diffrent, when a coin gets collected it calls a function. i can make it call the function that spawns a randomized coin
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
Or don't use _Color and use own property, that's likely the property the particle system is overriding for tinting.
ok so its first one then
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
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?
I'd just use easing formula or define animation curve
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
That's the point that you'd just use tween library
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
I hope wytea's still awake cuz it took forever but his idea worked lol
i dont know how to work with angles much, sorry
oh it worked?
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?
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 😛
Yeah, sounds like SO is the way. The approach does sound a bit weird to me.
Why not just handle it on the level of UIWindows and UIManager? The UIManager would hold references to all the windows and when one window is opened, others should close or something like that?
nvm this clamp code officially don't work for the other arm
the naive approach i wrote before is like basically hardcode
https://gdl.space/yubapuboni.cs
Its not much UI really that im toggling because Im just setting a parent active/inactive. but i still need some way to indicate which one to set active if im trying to create a script I can reuse
oh i already figured it out, i just need to switch what object the randomizer spawns, sorry for making u do all this work
Do you plan to have so many different menues that hardcoding them is not an option?
randomrange handles all the work
not really, i think right now its like 5. I am also really considering leave it as the hardcode option because I dont want to overengineer. I was just considering this too incase I want to reuse this script in future games
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
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.
@prime sinew finally, inverselerp in action! https://streamable.com/62puia
The right one doesn't work, time for an hour of fixing
And then you can expand on it by nesting windows in windows to make sort of an hierarchy. So when you disable a parent window, everything below it would disable as well.
is there a reason for it to be physics based?
and can the claw be asked to close midway of closing
or is it always the full range of motion
it looks cool btw
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
sounds fun
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
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
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.
You can keep several "root" ui objects that exist(or a re persisted between) in several screens/situations so that you don't need to duplicate them.
Yea ill just stick to this easy method then, i was kinda reluctant with SO as states because it also just feels weird
i probably could have described this better to avoid that confusion, thanks still
@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
I personally wouldnt go with a disableList, I just disable everything. If its not in the enable list, its not enabled
Fair, depending on some situations you might want the ability to specify but def. not necessary
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
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
make sure your unity projects are ignored by windows defender and look into disabling domain and scene reloading and see if your able to use it
wait you can disable domain reloading
thank you
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
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
Hey, before going further, you should configure your IDE
!vs
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)
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
The issue is, in your Update where you set the velocity, you don't have a check to see if you're dead
the cool stuff isn't working as it should
I didn't ask you to install visual studio, the message asks you to configure it
It doesn't recognize Unity properties
Also worth dropping the bot message about sharing code too (i dont know the command)
oh ok so i need to download it on unity to have it connected simultaneously?
I thought they were already, ok
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
ok thank u
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
sounds good
Your question was well typed btw, good amount of information. a lot of people struggle with that
yep, supplying the error message and the code is appreciated. in the future, do follow this guide on how to share code though
!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.
@valid raven
Aaand, achieved! @prime sinew https://streamable.com/cvmewt
https://hatebin.com/ajmjgqoyhv here's the code for this stuff, needs hinge joints and some scene work but I wouldn't have it without you, so enjoy lol
yeah truth be told i m bit lost, completely new here.
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?
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
It's alright. Feel free to check the pins in #💻┃code-beginner for some useful resources too
Try looking into replacing the animationClip within the animator, maybe?
I mean I already had visual studio and unity on and all.
My bad, it's something you can program with
no you're fine it was my misunderstanding
awesome!
the point i was making is configuring your visual studio to work with Unity
if done correctly, it'll be underlining errors and autosuggesting properties
you're welcome
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
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
ok so i checked, I already had it installed in unity and all
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
where do I find IDE?
ok it's in 2nd image that I posted earlier?
i want to see the current state
to see if it's configured
which is the entire point of this convo
is this ide?
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
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?
i already told you
like die = movementstate = false?
you need to set a isDead boolean to true when it dies, and only set the velocity if the boolean is false
thank you
https://gdl.space/raw/pudayefedo
does that work better? still cannot figure out the correct code to it @prime sinew
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
Okay. So you set a bool to false
Where did you use it to make sure velocity is only set when it's true
hi so I've been using this basic coding site called "scratch" for a while, any good ways to transition from scratch to unity?
You just need an if statement around the code that sets velocity in Update
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
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
I gues, can we see code?
Wait I wills et up example script and see what happens
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 :/
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
I've invited u to the netcode server but no, you can not pass gameObjects. What you can do is get the NetworkObjectId from the NetworkObject component and pass that (it's a ulong) through an RPC. Then on the reciving RPC you can grab the gameObject with:
GameObject object = NetworkManager.Singleton.SpawnManager.SpawnedObjects[NetweorkObjectId].gameObject;
oh, okk, i saw the invite, but ok thanks i'll search with this
mb
is this attached to an object
It's working for me. Mayb check the inputs in the projects settings. If not I don't think it's a code problem. Maybe someone at #🖱️┃input-system can help you out.
Yes
are there compiler errors @unique robin
maybe in player prefs ?
No, I would think It is in ainput error
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
are you using the new input system, or the old input manager
you should clarify that
@unique robin
I am not sure haven't uopdated in a while
I am pretty sure I am using new input system
did you check?
using unity 2021.3.5f
that does not matter
your unity version does not matter. it's what your project is set up to use
if you are using the new input system,
https://www.youtube.com/watch?v=0z-6lxL_sS4
I often use the old input system so potentially I'm not using the new input system and trying to use the old
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
yes
ComputePenetratoin - if the output distance variable is above 0.0f then there was no penetration ?
The distance is always positive. It's the distance the first collider must travel along the direction to separate from the second collider.
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.
it works now thanks
So I made a sprite library. Why am I unable to add it to the gameobject Sprite renderer and the animation timeline?
Following this portion of the manual BTW.
https://docs.unity.cn/Packages/com.unity.2d.animation@6.0/manual/FFanimation.html
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?
well I do see one bug here
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
ok damn that is very weird, it doesn't show anything in the inspector, but it works as perfectly as it can???
thank you very much either way, but that confuses me
This is expected
listeners added with AddListener don't show in the inspector
The only way to add the inspector ones is with this: https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.AddPersistentListener.html
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.
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.
what .net sdk should I download?
But an enum is essentially an int with a human readable name.
Something like this by any chance?
That would work!
I have a second script for customizing the character, but it also needs to be saved when everything is picked
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
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?
You might have two instances of GameManager, one with it assigned and logging correctly, and the other with it unassigned and failing to log the count.
no more logs, i'm pretty sure there is only one instance
Which line are you getting the exception? And why does it appear as a regular log message in your console and not an error?
that says 624
not 264
and it's likely the line of the Debug.Log in your catch block
what
anyway - it's pretty clear blockSprites is not assigned
I noticed accessing the rotation.eulerAngles.x of a transform returns strange results. I'm getting something like:
you cannot read a single euler angle in isolation and expect sane results. Euler angles are intricately tied to the other angles in the set due to gimbal lock
where are you getting the line number of the error from then
that says 265 now
one issue here is your use of the ?? operator
that doesn't work properly with Unity objects like Texture2D
It is already in the code snippet I provided.
Hmmmm, how can I go about reading the rotation for a transform then? I'm trying to make a camera look script, in which I want to check the current rotation to avoid looking beyond straight up/below straight down (to stop the user from snapping their neck to look behind themselves)
yes, but did you notice in their example they do not lock the cursor?
you should track the pitch of the camera in your own float variable and clamp that
or use Vector3.SignedAngle to get the proper angle
this got it fixed, thank you @leaden ice
Ahhh okay, then just assign the camera to a new rotation each time (based off the current up/down look angle float)
Yes, I am also not locking the cursor, It works when I am locking it but I don't want to. I have just confined it for game reasons, now I remove the confinement as well.
That worked beautifully, thank you!
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.
Finite state machines are worth looking into. They’re relatively easy to implement.
If you wanted something more complex look into behavior trees
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
GLGL
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.
Mutable ScriptableObjects at runtime
one option is:
public MyScriptableObject mySo;
void Awake() {
mySo = Instantiate(mySo); // now it's a runtime local copy that you can freely modify
}```
i see. and I would need to use reflection to make a deep copy? which I assume is what steve’s package does automatically?
I prefer to just keep the SO immutable
and to track any modifications to that base state separately
How deep of a copy do you need?
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
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
"Deep copy" means that references are also recursively copied
changes are only applied to an instance, so I want to keep the original under lock and key
from my experience, when you ask about how to do a "deep copy", you're doing something the hard way
if this is already the case then Instantiate is a "deep copy"
i see. would it automatically get destroyed/garbagecollected when done?
as always
No, you will need to call Destroy on it
oh right, yes
in OnDestroy
Since it's a UnityEngine.Object
It wouldn't die during a scene switch, right?
this feels a bit dangerous, but I can handle that. I mostly want there to be zero chance of ever modifying the original
since it's not part of a scene
maybe I should make a childclass of my SO to avoid getting tripped up?
like EntityData: SO, RuntimeEntityData : EntityData.
RuntimeEntity data is mostly an empty class
it'd have a constructor that takes a T and instantiates it
hmm, maybe I should look into stevie’s package.
May I DM you
Object as Unity.Object or System.object?
No, Sprite is not a UnityEngine.Object
use System.object, will work
object o;
Sprite sprite;
if (o is Sprite) sprite = (Sprite)o;
Should be able to. Not sure what Steve is talking about:
https://docs.unity3d.com/ScriptReference/Sprite.html
Can you explain what you mean by "it just fails"?
If your object is not actually a Sprite then it will fail
you can just do print(myObject.GetType().Name)
which you are trying to make a Sprite from?
if you need a sprite from a Texture2D you would use https://docs.unity3d.com/ScriptReference/Sprite.Create.html
I did
I was trying to assign it to an Image directly out of the method that casted it
Now it works
not sure I totally follow but, glad it's working 👍
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
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
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
Can you check what is getting serialized in the yaml? It seems like it's serializing the sprite in place, like it doesn't have an asset it can reference by GUID.
@late lion sorry I dont know what the yaml means or how to check this
To start with Lot_AnimationFrame does not have a parameterless constructor, that is going to upset serialization/deserialization
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.
@knotty sun oh ok I see. I'll try that.
Doesn't seem to make much of a difference. Actually hold on
If this is getting saved as part of a scene, you can open the .unity scene file in Notepad to inspect the yaml and find your variables, like "animationSequence". Or if it's saved in a prefab, you can open the .prefab file instead.
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
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.
there's no need to use any reflection in such a setup
you can mark the fields as protected
through public properties on the child
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
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
I don't really know what to make of this, nor do I understand why it's talking about Seralization depth just because I have a sprite field tbh.
I am simply storing sprite references in scriptableobjects
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
if i don't serialize i can't see it in the inspector
And they are definitely assets and not runtime generated sprites?
yeah
Maybe silly question but have you defined your own Sprite class?
I haven't no
I don't recognize this "length: n" under each sprite. I don't have that in my own scriptable objects that are serializing sprites.
its part of his struct
Oh, my bad
yeah it's just an int in the struct
can you screenshot the inspector for the SO
yes just give me 5 minutes for the rebuild to finish timing out
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.
can you please post your code to a paste site
!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.
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?
I don't see any problems with the code. This might be some weird Unity bug that will require nuking the Library folder to fix.
character controllers get mad when parented, don't they
I could try nuking the library folder
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
random errors that make no sense
this is the SO
nothing wrong with that or the YAML file as far as I can see
Character controllers get mad period lol
i suspect that unity is unable to update the .asset file because of the serialization depth limit
so we aren't seeing the actual problem
I see no reason for this to happen, so i'm blaming library demons
but why, this is the kind of stupidity I would expect from 2022 not 2021
we're brushing up against one of the two hard problems of computer science: cache invalidation
https://gdl.space/divihuseba.cs idk if this works. you are missing the scriptableobject tho so idk if you can make much use of this.
rebuilding the library now i'll get back to you
Thats perfect, I can make my own SO
It seems to work fine now
Not complaining about the serialization depth either
so I guess it was a library quirk
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 🤷♂️
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.
@sudden meadow Works for me so i guess it was just a wierd bug
Yeah seems like
I need to dig into how that kind of corruption actually works at some point
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
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
@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
but its not phasing through objects like it would if it were travelling too fast
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
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
intellisense use it ;D
i misread yours as (Collider2D) rather than (Collision2D)
thought that was the difference
how do I access the colors in project preferences from script
which colors specifically?
like the editor theme colors?
I've never tested if that actually changes with the editor settings
but I imagine it does?
seems to work, im not trying to change them, just use them for drawing debug stuff
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)
{
}
}
I would use scriptable objects
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?
This is a pretty decent implementation that I have used before https://www.jonathanyu.xyz/2016/12/30/buff-system-with-scriptable-objects-for-unity/
it would loop over its power ups and pass the data for each one
What do you mean here, on this part?
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.
- Do these powerups need to "Stack" with themselves, IE can you have for some buffs 3 copies ("Stacks") of the same buff?
- Do they have expirations, and do you want/need to track the expirations individually
- If you answered yes to both above, do you also need to track the expirations individually for each individual stack of the same buff?
I usually make a class like "ModifiableQuantity" which can take additive and multiplicative modifiers. I use that as the "damage" variable on my abilities. The powerups then just act as a modifier on that ModifiableQuantity. In general the value is mostly cached and only computed when adding/removing modifiers
yep, that's the deal
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?
I do like this for like an RPG style game with more static modifiers but these are meant to have high impact and I also plan on them being able to interact further out. say spawn a gameobject on the player for a visual buff and let the Powerup handle when it shows/what it shows.
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.
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.
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!
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?
public class DiffAttack : Attack{
public DiffAttack() {
damage = 3; // will work
}
}
will work
cool! thanks! (how did you color the code in c#)
!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.
also cool!
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)
Are you trying to make a custom mouse cursor?
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
Simplest way is basically to set your canvas to Screen Space - Camera.
Then you can project your mouse position to world space and position the ui element there
basically:
Vector3 mousePos = myCam.ScreenToWorldPoint(Input.mousePosition);
tooltip.transform.position = mousePos;```
and again - this only works in Screen Space - Camera
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;
}
you're doing !IsTransparent so you;re actually checking if it isn't transparent
you're also adding every pixel to that list which is going to grow quite large 😮
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
your code is only checking if there are any transparent pixels in it
is that what you want?
It will stop when it gets to return true; ofc
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
I don't see how that part is really relevant
also
you are anaylizing the entire texture every time
not just the individual sprite
And of course: #archived-code-general message
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
It's the entire texture
using the sprite of course
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
and, don't forget the most important thing here that I keep mentioning:
#archived-code-general message
which is not the same as all transparent
Oh wow that makes much more sense. Thank you!
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
You could disable gravity on the player when it's a child of the airship
Or set a negating velocity of y +9.8
It's not "gravity" as in like I have gravity enabled on a rigidbody, I'm just moving the charactercontroller down to simulate gravity, but if I were to stop doing this then the player wouldn't be able to jump
You could also set the ship to kinematic
While not moving*
then it won't respond to collisions right?
Kinematic rigidbodies respond to collisions
once it starts moving if I set it to non-kinematic (enabling physics) it'll immediately start to drop again tho right?
It won't respond like it's being pushed
The ship? I thought you said it ignored gravity?
I had to double check the unity docs there but from the docs:
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.
yeah I just disabled gravity on the ship's rigidbody, but it's the player pushing down on it that's forcing it downwards
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
It means being pushed, but collision EVENTS still happen. That's what I thought you meant, sorry
ahhhh gotcha
So the PUSHING is the collision that wouldn't happen
The ship won't be pushed around while Kinematic
Which could be an issue if you want asteroids to do that
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?
However, if you want to do kinematic, you can make special collision events for this cae
but if I make it non-kinematic it'll respond to my player
No. It would stop, but not bounce
Depending on the wall rigidbody/collider settings of course
gotcha
well yeah my wall would probably just be another kinematic rigidbody, its not gonna move or anything
So it would stop and throw an OnCollisionEnter event that you could handle manually I guess
gotcha, so I guess I could just like calculate how hard it should bounce off the wall myself and apply that to the rigidbody
Exactly
okay cool, I'll try that out and see if I still need any help, really appreciate it guys
np
You could do like a trigger collider and when it gets close to walls and things it turns into a non Kinematic rb, so that it bounces correctly, then on exit set it back. It would be pushed down a bit but it miiight work.
You could even remove the player as a child so they go flying haha
I dunno if that would be worthwhile at all lol
lmao I mean it's worth looking at, maybe I could disable the character controller for like a couple hundred milliseconds so the rigidbody's velocity sticks once i turn it back to kinematic
seems janky though, I'll try manually calculating it first
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?
you need if (!this)
but really you should just - not call whatever function this is if this thing is destroyed
I'm just fixing a package I imported
it removes the call from the event that called it inside that if
i know i can just make it move along the spline, but don't know how to access to other stuff
it did work, thank you
is anyone experienced with parrelsync? i'm encountering an issue where scriptableobjects don't match the parent project, often in strange and random ways
Is the data that doesn't match serialized?
one sec, let me find an example and check
it's happening primarily with a field that i have an attribute attached to
what attribute?
[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?
is the id field not serialized?
I can't imagine it's much use without being serialized
It's visible in the inspector because you literally have a property drawer drawing it
EditorGUI.PropertyField(position, property, label, true);
is it serialized?
i'm unsure of how to check outside of inspector visibility
it needs to either be public or marked with [SerializeField]
i assumed it was because of the propertyfield docs describing what it creates as a serialized property
and it needs to be of a serializable type
it is public, but let me try it w/ serializefield
it will make no difference
public is fine
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?
it moves the CharacterController twice in that frame
YOu can but you should really only do it once per frame or it will be buggy
.move is a function also, you can call a function however many times u want
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
yeah i'm following a tutoriel and they used it twice without explaining. didn't know they added up. Thanks!
You can and should combine them. For example:
Vector3 horizontalMovement = move * speed * Time.deltaTime;
Vector3 verticalMovement = velocity * Time.deltaTime;
controller.Move(horizontalMovement + verticalMovement);```
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)?
Everything in DOTS doesn't touch GameObjects, so I imagine all the normal stuff is how to do it.
The main thing though is you're not allowed to do any GameObject related things on any thread except the main thread
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
I think you should definitely ask in #1062393052863414313 because I've never used it
re: my earlier issue
you just need to add ```
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
after the guid changes
to sync the change to parrelsync
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?
void MyFunction(InputAction.CallbackContext ctx) {
bool isPressedCurrently = ctx.ReadValueAsButton();
bool wasPressedThisFrame = ctx.started;
bool wasReleasedThisFrame = ctx.canceled;
}```
lemme try that real quick
ok that did not really work, can you tell me how I send my code to you?
show your code and also very importantly show how you set up the input action
and explain in what way it didn't work
I have a bool called is firingcontisully but the bool does not change
what do you mean by "change"?
It set it as false in the start and it remains as false even when im touching the the button
how arew you checking what it is
Also you never shared:
show how you set up the input action
isFiringContinusly is a public
so you mean you're looking in the inspector
yep
And please show this
I have it set up as an event (the onFire is the is the one where focusing on)
yeah but i want to see the configuration of the action itself
The "Fire" action
Also this^
the input dected is printing
is this what you mean
get rid of the tap interaction
ok on it
also it's not going to "continuously" do anything really
this will only be called when you actually press or release the button
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;
}```
The tap interaction changes how everything works
don't do it if you don't know what you're doing
thank you so much man you are a real one
yeah it seems like this isn't true, or at least I can't figure out how to get the OnCollisionEnter event to fire. I have a cube with a kinematic rigidbody and a box collider (I also checked provides contacts) that my ship is trying to collide with, and then my ship is a rigidbody with a collider on one of it's children.
The rigidbody and collider are on different objects though (for the ship)?
yeah, I just tried putting a box collider on the ship though and it didn't seem to make a difference
Heyyy
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
Holy moly i can ask my questions after long time
yeah, the thing it's colliding with actually has a kinematic rigidbody and a collider on it
Hmm, not sure. It SHOULD work. Did you touch the collision matrix?
nope, haven't messed with it at all
lemme send a screenshot or two just to make sure im not completely overlooking something
I would put a debug in the oncollisionenter, not behind an if or anything
Just to help with checking
Hmm ok, and the debug never fires... weird
yup, not really sure why it wouldn't
Ah dang
https://docs.unity3d.com/Manual/CollidersOverview.html
Looks like one has to be non kinematic
I just created a cube with only a box collider and rigidbody and if its non kinematic it works
yup, sounds about right
guess im back to square one
Yeah sorry!
nah its all good, it was a step in the right direction I think
Note I host a much more readable version (imo) of that graph here fyi
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
Unity does not use .NET 6. It uses a modified version of Mono, that's based on .NET Framework 4.7, but with modifications to allow a subset of C# 9 and .NET Standard 2.1 features.
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.
Yeah I was being dumb and thinking c# version lol. But this is the status for .net
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 :>
second attachment is called upon switching dropdown options, btw
coroutines can only run once (or something)
Coroutines can run as many times as you want. You just have to call StartCoroutine each time you want it to run
In your second screenshot it looks like you're trying to fade your sound in AND out at the same time
so it's supposed to work then
it's called once at the start and the SetThemeis called everytime I switch
yeah, and it works fine
problem is I can only select each theme once
Probably because your audio sources are not set to loop
so once they play, they've played
they are TwT
time to start adding logs
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
sounds like yhou have multiple coroutines competing with each other
there's only one tho
you wrote one coroutine method, but you are starting it many times in many places
wait, is it maybe that you can't start the same coroutine simultaneously with different parameters?
you can
there's no limits on calling the coroutine
ah
SetTheme calls both only once tho
and how many times are you calling SetTheme?
once everytime I switch dropdown otpion
Maybe add a log to it and make sure it's not being called more often than expected
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
Un-collapse it please so we can understand the sequence in which events are occurring.
Relative to the logs.
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
save it in a separate member variable
but yeah this makes sense, once it goes to 0 it will never come back up
because 0 * anything is 0
it's what i noticed x)
you'll want to save the "max volume" variable somewhere
and never change that
so sound.voume = maxVolume * i; should be in the loop
hmm I dunno how it couold be done tho
?
I stuck to this for now, cuz of all em have 0.5 volume
but why is that so hard?
also volume is almost definitely not 0.5
nvm audiosource volume is 0-1
so that's probably ok
well, how can you set maxVolume once as a variable outside the coroutine?
float maxVolume = 1;```
or even const float maxVolume = 1;
yeah, but shouldn't it depend on the sound.volume in some way?
why so?
well what if one theme is slightly louder than the other, meaning i'd have to set it to 0.4, for instance
then you could do something like:
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];```
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
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.
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?
PropertyField
thanks
You would create some class or struct to hold these variables then have an array of that class or struct. Could also do with tuples but you really shouldnt need to do this often
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
ig a Dictionary<string, int> would do
dunno much tho
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
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?
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?
Yeah they are, ill look into scriptableobjects
not really sure if this is the best way to do it ngl
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
Hello friends, I'm experiencing an issue related to JSON parsing. Could you please help?
Said in a friendly way: don't ask to ask
https://dontasktoask.com/
Just say what you need help with
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
You seem to want me to explain my question in a detailed manner, as far as I understand.
Well, just in any manner. You have an issue RELATED to Json, that's all we know as of now
Ah, that's annoying. I dunno. It might have to be a custom editor script unfortunately. Check here
https://discord.com/channels/489222168727519232/533353544846147585
it means dont say "I have a question", just say the question
saves chat space and people can get straight to answering
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.
I understand, sorry
Breakpoint it, debugger attach, see what the actual raw string value is
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.)
I just discovered that this exact issue has been a known bug for over a year now, its specifically an issue with the modern editor UI for arrays
the old UI doesnt have it
Oh really? 😂 sad but also a tiny bit funny.
Sometimes when we move forward we stumble I guess
probably something to do with the elements being reorderable being broken, since turning that off is what fixes it
it was fixed in a later Unity version, but i forget which
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
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
the irony, as I just now learned, is that it was fixed the very next year from the version I'm currently using(2021)
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
it was fixed in 2022
I started my project in 2021 and out of fear of file corruption chose not to update to the next version
well, can always make a backup and experiment on upgrading that. that's all
true
Currently having Schrodinger's bug
Race condition calling it now
...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
I'd maybe think it's perhaps your inputs are doubled somehow or something
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
You can't process input in FixedUpdate
Or that happens
Input processing goes in update
gotcha thank you
Anyone got help for the... confusion
this will work fine right?
Try and see
hello to all, anyone know how can read a json and convert into a object list?
Unity's JsonUtility or Newtonsoft JSON for example
Basically any json parsing library
i try to use newtonsoft but cant add into my proyect
Newtonsoft.Json (Json.NET) 10.0.3, 11.0.2, 12.0.3, & 13.0.1 for Unity IL2CPP builds, available via Unity Package Manager - jilleJr/Newtonsoft.Json-for-Unity
ive forgotten how while loops work
i know youve gotta return or else itll crash unity
but thats not working right
No you need to just not make the loop infinite
oh
It will run untill the condition is false
i want it to run as long as a certain button is pressed
You don't want a loop
i had it like that without return but it crashed unity
oh
Then your condition never became false
it would when i let go of the key
Doesn't matter because the next frame will never run
Input is only processed once per frame
At the begining of the frame
if i use a if statement it still only runs once on each key press
if statement with what condition
maybe i was using the wrong input thing
ah now it works
the gun is not using the correct ammo type
if I fire my Assault Rifle (AR ammo), it fires Buckshot. if I fire my Shotgun, it fires Rocket. how do I fix this?
https://hatebin.com/ozuuvpjlwq GunCore
https://hatebin.com/meqmfzkfba AmmoMaster
This is frustrating and I hope someone is able to help you but you have to admit that's at least a little funny

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?
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
Are there any good Unity Open Source game/projects out there?
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
Either _items or items[j] is null
Since you initialized _items in line 43, it should be items[j] that's null
Yeah
Check _items[j] then
and j is 0 basicly
from the print its seen that its not
Is the error message recent
Like the line number hasn't changed by you changing the code
if i just print _item, it just shows Item, so i print item.name and it shows correctly
🌈 use the debugger
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
where is this debugger
no one wants to 🥣, learn how to debug 😊
its just an array extending function, a simple answer wuld be best
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
well how do i assign it a value
new
Item[] _items = new Item[assets.Length + 1];
and what does this do then
doesnt it give it default values
i see
Again, please learn the debugger, it takes 1/2hr and then you're set for life
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
Sounds like someone whos never used the debugger
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
i wuldnt have guessed that i have to make a new class() for every entry
You don't, you only have to make it for the one that is null
Anyone have an idea how to disable Button GameObject in Script? SetActive(false) doesn't seem to work.
well theyr all null since its a new array
but you're writing elements into it, so those will not be null
Show your code and what you're trying to disable
Do you want the button disabled, or set uninteractable, or the gameobject it's on deactivated?
if your refering to the ones in the loop, that loop doesnt run when i extend it the first time, since its a length of 0
and id bet ill get an error for the loop if i dont put new class() for every iteration
With the way you're doing it, yes, you have to new each one
is there another way of doing it?
Depends whether you want the arrays referencing the same objects or not
the entire button, as in the gameObject checkbox
Also, why not just use a List?
Then button.gameObject.SetActive(false) would do it
im just extending an array, theres no other objects
forgot about the gameObject part :/
becouse im an array andy
You're creating a whole new array every time you call this method, you are not extending anything
i know
So, do you want the new array to reference the same objects as the original one?
yes
Then assign them directly instead of assigning each member one by one
Or use Array.Copy or something
well how do i resize it after that
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
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
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
well your not making much sense to me
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
the debugger is not nececery here, the whole code in question is in one function, and is basic
[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 ?
You can do Array.Resize(ref _items, _items.Length + 1), then set the last value of the array using _items[_items.Length - 1] = newValue, though if you'll be resizing the array a lot, I suggest you replace the array with a List, since it gives you access to the Add(), and Remove() functions
No
is there any way to modify Unity's Tilemap system to allow per-tile data storage?
mega unfort 😔 ✊
like storing a health value that can be accessed and decremented, but only effect the one tile
what do i need to use for Array?
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
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
Array.Resize(ref assets, assets.Length + 1);
assets[assets.Length - 1] = _item;```
so this basicly
and with _items[^1] = newValue we can further reduce the hellcode to nothing and it will disappear from existence
assets[^1] = _item; so just this?
this doesnt work
What's the error?
Unary expression should work unless length is zero or something.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges#systemindexcs var array = new int[] { 1, 2, 3, 4, 5 }; var thirdItem = array[2]; // array[2] var lastItem = array[^1]; // array[new Index(1, fromEnd: true)]
Maybe they're on an older version where indices aren't supported
But who knows, without the error message
my moneys on they didnt assign _item to be a thing
is this a question better suited to #archived-code-advanced ?
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
I don't think it's possible tilemaps are just for displaying and creating a collider, if you need any custom scripts on a specific tile you are going to have to use prefabs i think
Doesn't sound like a code question but a feature or some other request. Maybe #💻┃unity-talk or the non discord server if you're okay with non immediate but more thorough responses.
my money's on them removing the other line of code and expecting it to work. Hence why they said "so just this?"
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?
out of range
So a length of zero