#archived-code-general
1 messages Β· Page 128 of 1
fair, I was distinguishing the wrong things there. I should've said that the Texture2DArray object you created is distinct from the asset that gets produced from it.
The behavior is certainly a little bit unexpected.
Let's say I expect a value to be within the range of -1 to 1, and I want it where:
- If it's 0, it's 0.
- If it's above 0 it's 1.
- If it's below 0 it's -1.
Any quick math method to get this behavior?
Mathf.Sign
ah wait, that returns 1 when it's 0
use Math.Sign instead
https://learn.microsoft.com/en-us/dotnet/api/system.math.sign?view=netframework-4.8.1
Thanks.
Odd that the unity one has that behvaiour.
0 is not positive unity π
read the error text
The name 'StartCoroutines' does not exist in current context
well there you go, you're trying to use something called StartCoroutines but that doesn't exist
do you see it underlined in red in your code editor?
no
or visual studio code
then you need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
after you complete those steps, spell the method name correctly. it's StartCoroutine
0 is positive
-0 is not positive
what is this person using in order to have 2 values in each item of their list?
an array of a class or struct
because Requrement is not seriazable
no it is not
btw a ScriptableObject does not need to be flagged as Serializable
okay thank you
it you want to serialize Item it needs to be flagged Serializable as well
I seperated the scripts, made Requirement serializable and still nothing
my item is a scriptable object
how are you creating your SO's? I see no CreateAsset Attrbute there
the create asset menu is in the Item scriptable Object
and for RecipeSO ?
I don't know if Unity will like constructors on these scripable objects
ffs
my bad
even so what @simple egret said, you cannot have a custom constructor for Item
yeah this is come off as stupid
if i wanted to replace m1911 with a prefab from a script and keep the same position in the children array as its referenced that way in other scripts
Okay, what's the question here..?
.child(0) = prefab
That's not a question
If what you want to know is how to set the child position in the Hierarchy, then Google "how to change position of child in hierarchy unity"
you realize when you change 1 item it will change all of the scriptable object
removing contents does not remove the index of the array if that's what you're asking
yes
oh so i can just destroy and instantiate then?
as long as you use the same index
This is also a lesson to try not to have your logic depend on child order. Just add to a list or cache to a variable
just making sure you're aware :p
They are misunderstanding you
It's not the order in an array, it's the one in the Hierarchy
Ah, right yeah that's a little different
@topaz sapphire
if you did GetComponents it would just give a temp array basically of the references
Don't know if you're having trouble with the spawning, replacing, or ordering of the child because up till now you haven't actually asked a question
i have man
"if i wanted to replace m1911 with a prefab from a script and keep the same position in the children array as its referenced that way in other scripts"
do i NEED to put a question mark after?
Okay... And which part do you not know how to do
That's just an if statement
Do you know how to spawn an object?
i beg of you to kill your ego for 2 seconds dear god
keep making remarks then
@latent latch can you give me a hint?
you seem to know what your doing
They don't know what part of it you don't know how to do, and these are the questions you should be answering:
Don't know if you're having trouble with the spawning, replacing, or ordering of the child
What do you know how to do out of the question you asked, because there's multiple steps, just destroy the object, spawn it, then change the sibling index using the transform APIs
There's a bunch of methods relating to shifting placement in the hiearchy that may be what you're looking for
man look, "thats just an if statement" and "okay... whats the question here?" and then walking around the answers already presented aint remarks then i dont know what is
thank you
thank you
Yeah, you can just assign the sibling index if it's in the correct transform list
otherwise just move it to the first index if you're using 0
so delete, instantiate, update index
in what way did that not work?
that text 0_0
yeah that font is a war crime
is that terraria
not as bad as comic sans
even the activate windows is corrupted
this just gets more and more chaotic
id believe u if u said u were coding this on a samsung fridge at this point
yeah it didnt work because I forgot to call the function under the condition
it worked
Good evening friends.
I need to fire a sound via a audio clip. I have AudioSource and AudioClip in a empty child object called Audio Manager
But in my PlayerController, how do I access the clip from the other script?
get a reference to the object. here are several ways you can do so: https://www.youtube.com/watch?v=Ba7ybBDhrY4
ok π
this is my AudioController.cs in Audio Manager gameoject
using UnityEngine;
public class AudioController : MonoBehaviour
{
public AudioSource source;
public AudioClip torpedoFired;
}
this part is fine right?
i linked it in the editor too
sure
ok
If you prefer text guide, there's also this
https://unity.huh.how/programming/references
it's not really controlling anything here so the class name is kind of poor since it's just holding references to two objects. but i assume you're likely going to add some more functionality to this component?
video is better, adhd likes video
@somber nacelle not sure yet :/
where would you put your audio?
its a simple copyright clone of space invaders but my spin on it
for fun, not release/sell
all 2d
i subbedy to you too π
ty too
Hey, sorry about earlier. I should have just asked for which part you needed help with, instead of picking on how you asked for help
yeah its alright man, just try to holdback on those remarks they come off the wrong way without tone
void PlayTorpedoSound()
{
audioManager.GetComponent<AudioSource>().clip = false;
}
well this is a fail
that line doesn't make any sense
i got the first part right but not sure what to do at the end of ().
public class PlayerController : MonoBehaviour
{
[SerializeField] private GameObject audioManager;
if you want to put nothing in the clip property then assign null because it's not a bool
ok
but also, just reference the AudioSource directly, you don't need to reference the GameObject just to then call GetComponent on it
how do i do it direct then?
everything is different now in 2023, last time i did a clip was 2015
XD
Reasons to not make video tutorials: they're hard to update π
Unity Learn sucks as bad
use the component's type as the variable type instead of GameObject, you know like i said in the video π
some of the stuff they have you do is missing/moved
My site doesn't though, which was the text one that was linked
ok
ok
i got the reference part but this is losing me
void PlayTorpedoSound()
{
audioManager.GetComponent<AudioSource>().
}
what goes at the end of .
You don't need to use GetComponent if you have referenced the component directly
ok
Do you have proper autocomplete and error highlighting in your IDE?
because you should be able to just see the members and access them easily as you type
yes but grr π¦
Fast tutorial on how to play audio clips in unity using a C# Script
hes using PlayOneShot
I dont see that :/
even with the reference
Your audio manager is not an audio source though
it contains the variable that you need to reference first
you changed the variable type so you have to drag the object in again because it was previously serialized as a GameObject type
ok got it
[SerializeField] private AudioClip torpedoFired;
also dragged the CLIP in
but where is playoneshot?

that's the AudioClip not the AudioSource
AudioSource is like your radio
so do i want a clip or a source?
audioclip is the casette
the clip is the sound itself. the AudioSource is what plays the sound
void PlayTorpedoSound()
{
audioSource.PlayOneShot(torpedoFired);
}
we good i think ,testing
BINGO
ok it worked π
So whats the best strategy for managing audio and clips in the future?
sound manager
I would name the gameobject the same name of the script
fair enough, done
and yeah but as a singleton as well
why does things get more complex? soon unity is gonna demand 50,000 javascript libs :/
but i will check it out
javascript ?
was a joke since js is horrible in webdev
anyway reading, min
public class Singleton : MonoBehaviour
{
public static Singleton Instance { get; private set; }
}
So would this be in its own script in an empty object?
did you kinda just skim through the article ?
any monobehaviors needs a gameobject .
doesn't need to be called Singleton though
Yes, jsutneed a empty, name it Audio Controller as my script is named. and add a class with just the singleton to it
and call the singleton anywhere i need it for audio in my other source code
I followed this tutorial while trying to make a state machine to go ahead and add the movement to the player
https://www.youtube.com/watch?v=K1xZ-rycYY8&ab_channel=bendux
However, when I moved, I wouldn't stop moving when i let go of the key. To fix this for moving left and right, I added the line rb.velocity = new Vector2(0,rb.velocity.y); to my idle state, which stops the player when the state is idle. However, for jumping i'm not sure what to do. When i press space, the player just flies upwards at a steady pace and never falls back down. I'm very confused. Here is my script in the player (a lot of stuff in here isnt finished yet)
Learn how to move and jump in Unity!
Source code: https://gist.github.com/bendux/5fab0c176855d4e37bf6a38bb071b4a4
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
By the Fireplace by TrackTribe
H...
yea as it says use caution dont start using a bunch of static singletons everywhere, only when it makes sense to do so
sorry π¦
i will try harder
nothin to be sorry about just read the pros and cons lol
!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.
@grand trench
you should be doing the jump the same way the tutorial you're following is doing.
Is it not the same?
Yeah just give me a minute
@potent sleet
not gonna lie
void PlayTorpedoSound()
{
Singleton.Instance.AudioController.audioSource.PlayOneShot(torpedoFired);
}
looks way better and easier to access
noo don't access components directly
.... ok now what???
make methods
that is a method
not everything should be public
its called void PlayTorpedoSound()
yes
don't do that
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public AudioClip torpedoFired;
public Rigidbody2D rb;
public GameObject torpedo;
private float horizontal;
[SerializeField]
private float playerSpeed = 4f;
public void OnMove(InputAction.CallbackContext context)
{
horizontal = context.ReadValue<Vector2>().x;
rb.velocity = new Vector2(horizontal * playerSpeed, rb.velocity.y);
}
public static GameObject Create(GameObject prefab)
{
return Instantiate(prefab);
}
public void FireTorpedo(InputAction.CallbackContext context)
{
if (context.performed)
{
Debug.Log("Played sound!");
PlayTorpedoSound();
}
}
void PlayTorpedoSound()
{
Singleton.Instance.AudioController.audioSource.PlayOneShot(torpedoFired);
}
}
this is the playercontroller.cs
so how do i do the "method" way now?
Singleton.Instance.AudioController.PlaySound(torpedoFired);
there is no PlaySound
smh
Singleton.cs
you make the method inside the audiocontroller
using UnityEngine;
public class Singleton : MonoBehaviour
{
public static Singleton Instance { get; private set; }
public AudioController AudioController { get; private set; }
public UIController UIController { get; private set; }
}
which method?
PlaySound()?
ok
you're trying to run before knowing to walk
just my 2c : don't have to rush through it and take the time to learn the basics before mashing random code together
also your singleton class is missing the assignment
you're gonna get a NullRefException if you tried running it
using UnityEngine;
public class AudioController : MonoBehaviour
{
public AudioSource audioSource;
public static AudioClip torpedoFired;
public static void PlayTorpedoSound()
{
audioSource.PlayOneShot(torpedoFired);
}
}
Instance = null
are you troling or
NO
why is this static
public static AudioClip
public static void PlayTorpedoSound
I said im adding the damn code check now for instance
because it's what I use in C# to access certain methods
I willr emove it
defeats the whole point of doing a singleton instance
also you cant assign static fields in inspector
you wouldn't use static everywhere in regular .NET either
also unity is "full blown c#" just up to 9
there are specific things related to inspector and API unity only
oh ffs
where in the article is this the same ? btw
perhaps take a break
I don't get time to 'code' this is my time :/
11:12pm
else i could stop sleeping and just use those hours, i work full time in a deli :X
@potent sleet https://pastebin.com/wu3jFkkj
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
my bad for taking long i had to use bathroom
coding tired will just lead you to make dum mistakes like switching audiosource to static field and then trying to new () it π€ @pale spindle
fine :/
public class AudioController : MonoBehaviour
{
public AudioSource audioSource;
public static AudioClip torpedoFired;
public void PlayTorpedoSound()
{
audioSource.PlayOneShot(torpedoFired);
}
}
there nicer
i should now take a break
playercontroller:
public void FireTorpedo(InputAction.CallbackContext context)
{
if (context.performed)
{
Debug.Log("Played sound!");
Singleton.Instance.AudioController.PlayTorpedoSound();
}
}
removed static , i forgot to there
this is way different than the tutorial, why don't you implement that first then go into the FSM ?
its a older line, fixed
no more statics, im not using em anymore for this kind of stuff then
fair enough
i will get used to this new way, old habits i tried w/o any singletons/instances for audio
its not way different its just that the functionality is within a function
now im finding it out the right away, gonna reread your article and also @somber nacelle and @quartz folio
but its the same way he did it
just to be sure π
as far as i know
i meant within a method*
the jump functionality happens within fixedupdate, and uses the same line he uses
yet it works differently, why?
send the video again, dont wanna scroll up
alright
Learn how to move and jump in Unity!
Source code: https://gist.github.com/bendux/5fab0c176855d4e37bf6a38bb071b4a4
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
By the Fireplace by TrackTribe
H...
I'm gonna chill and work on things when my head is clear, im off this weekend so it helps
Else all I'll do is spin my tires and burnout. π
ok what does your jump look like, can you make a vid ?
I do like this singleton approach tbh π
it just goes up at a steady pace and doesnt stop ever
Thanks for slapping some sense into me @potent sleet
wwhich is the same thing my movement did but as i said in my original explanation, that was easy to fix
they are handy, just like everything else you use at discretion
Gonna netflix and chill and sleep.
Got it, will note it in Obsidian π
Ok, time to unplug my brain and watch something and go to sleep.
if it keeps going up is clearly not the same lol
Thanks again
case PlayerState.JUMP:
Jump();
sr.color = Color.gray;
break;
Jump() is constantly being called
ah
yup and video puts it inside a key
technically itβs the same line, but the difference is his is being called once
and yours is being called every fixed frame as long as the state is Jump
++ "Followed exactly like tutorial, they did not"
null
call Jump() when you press input, not when the state is Jump
omg
i just put the code in different places without thinking but i still followed how the tutorial made it
I beg to differ
what are you showing me
the video you said you did exactly like u did
as i said i used the same line he did i just put it in the wrong place
thats why copying blindly without knowing why its where it is is generally a bad idea π
^
null shut up
its ok maybe next time you won't do it again
i didnt copy it blindly asshole
im guilty of it sometimes
chill dimrod
i was thinking about what i was doing i just thought wrong
You need to chill
I mean it's just a suggestion not critisim no need to get pissy π
i made the wrong decision, not like i turned my brain off and just threw some code down
thanks again @potent sleet @quartz folio and @somber nacelle β€οΈ
gonna go sleep and play with stuff tomorrow again
have a good one
i got inputs to work so im happy too π

i actually didnt need to change where it was after all i just had to add an extra check to make sure you're grounded
so my thinking wasn't even entirely wrong
i just forgot one part
I am trying to set a boolean array by accessing an equal part of another Gameobject array which works but the problem is that the GameObject array auto populates the array but the player states will not and it makes me auto increase the length in the inspector does anybody know why?
https://gdl.space/ayimulagor.cpp
is there any way to use game objects or prefabs as a class
so like if i have a game object cheese cake
i want to get information about it's transform, rigibody etc in a script
Each script you put on an object, is a class.
right
if your cheese cake object has a CheeseCake class, then yeah
I guess thats doing what you want
i guess what i'm thinking is
if i need to add or remove components at some point
i don't want to manually have to go change my CheeseCake class each time to reflect that
but i guess it's not a big deal
For example, if you wanted to pick up the cheese cake as an inventory item, or eat it as some generic food item, you would use interfaces
Idk if that answers your question
interfaces are new tech for me so i guess i'll find out
You can always create a base Food class
and then derive cheesecake from it
I'm not sure what you mean by add or remove components though.
If you change from a rigidbody to a character controller, then yeah you'll have to go in and edit the code
i guess if you wanted information about its position, you'd have to get its transform, but if you wanted its colour then you'd have to ask its material or w/e
@carmine orbit the findobjectswithtag each time returning a new arrayβ¦
so you'd have to go find every component individually
and even if you just made a cheesecake class, you'd have to assign all of its values individually right ?
I mean, you could create variables. In Start(), you set each variable to the component you just searched for
then you just use the variables
like there's no "get all components attached to this game object" function or anything i guess is really what i'm asking
No, because that wouldn't make sense
gotchu
You could rig something up
that like, automates it
but no, theres nothing like that by default
ty
I need some advice. For my player movement script, what would you guys say is "best practice" to put all input detection and CharacterController.Move/other movement code all inside the Update method? Should I instead move all of the logic (including input) to FixedUpdate? Or should I use Update to store inputs as variable(s), and let FixedUpdate apply movement based off the stored variables?
If you put it in fixedupdate, you'll need to write your own interpolator
You can try gatcomponents<component> but ihavent try it before so i am not guarantee it will work, even if it works you will get a bunch of components that you dont know what they are
fixedupdate ticks at a fixed rate. Default is 50hz
you don't want to increase that rate especially if you're screwing with physics
The professional AAA way to do it, would be to run all simulation logic at fixed rate, and interpolate visual renders on frame updates
if you're just beginning, you probably don't want to do that
why can't you just do something like Mathf.Lerp(something, something, something * Time.fixedDeltaTime) in fixed update?
Because that's not how you lerp
If you're really curious, I could show you how to do it properly
if there is, it wonβt be as useful as you think it would be.
If you grab your CheeseCake GameObject and you know it already has a rigidbody using .rigidbody (doesnβt exist), itβs essentially the same as .GetComponent<Rigidbody>(). It would be a bit practical since less typing i guess, but not possible in c# without being extremely painful π.
Likewise, if you wanted a collection of all components (rb, renderers, custom scripts) on the game object, thatβs also possible using GetComponents<Component>() similar to what was said above me
So would the latter method be right direction then? So in FixedUpdate, only things like CharacterController.Move should be used. And also isn't detecting input only "reliable" in the Update method (and not FixedUpdate)?
understood, thanks in advance
float tickDelta = 1 / tickRate; // Time between each tick
float timeAccumulator;
void Update() {
timeAccumulator += Time.deltaTime;
while (timeAccumulator >= tickDelta) {
timeAccumulator -= tickDelta;
CustomFixedUpdate();
}
float interpolationAlpha = timeAccumulator / tickDelta;
Vector3.Lerp(myObjectPosLastSimulation, myObjectPosCurrentSimulation, interpolationAlpha);
}
void CustomFixedUpdate() {
myObject.Move()...
}```
I wrote this in notepad. Some stuff might be wrong, but the idea is correct
you cant use unity's fixedupdate
you have to make your own clock
interesting
otherwise you can't access the interpolator alpha
this is how it's done in multiplayer games
right, because Time.fixedDeltaTime is always 50hz (0.02)
I was wondering about that
yeah, you wouldn't use fixedDeltaTime
just regular deltaTime
all we're doing is accumulating time to figure out when the next tick should be
i see
I'm assuming tickRate would ideally still want to be 50 to be as close to the normal fixed timestep?
Or it could be faster if I understand correctly
cod warzone uses 10hz tickrate
it can be anything
lower it is, better performance you'll get
but less responsive
because Update (on most new systems) will be called much faster than 50hz
Correct. Calling character controller updates or doing anything intensive in Update() is a massive waste
I see. This is a great point that I never even thought to consider until now
Thank you for this
So in theory FixedUpdate would only be useful for stuff involving custom physics?
You can run any custom physics code in the CustomFixedUpdate I showed you above
That's really all unity's FixedUpdate is doing
there's nothing magic about it
but
you'll need to manually tick the physics engine
I'm just wondering what FixedUpdate is useful for then
So in this example (which is my ideal usage) is myObject.Move()... not physics code?
It can be a character controller, or rigidbody velocity sets, add force, etc
You'll need to disable automatic physics updates
and run this at the end of the while loop
Generally we call it a "Simulation Loop"
all simulation data should run on a fixed basis
so like shooting guns, moving, etc
kind of arbitrary but for reference older source games are 64 or 66, i think competitive cs:go servers are 120
So why is CustomFixedUpdate invoked in the Update method? What if the frame update stalls for a while (lets say 1 whole second for some reason)
Easier said than done
especially when you're only running a map with 8 players with raycast guns
and nothing else
true
That's why theres a while loop
the while loop catches up in case your game locks up
so yeah, you could have 2 simulation steps running in the same render frame
not uncommon
Ah yes good point, I didn't realize that
I see now
Sorry for my ignorance lol
Thank you for the explanation
You're getting it better than most people
If you put it inside VS and format it correctly, you'll be able to read it a lot better
If I'm being honest this seems like a game-changer (literally) π
ECS is the real game changer if you're looking for raw performance
This in particular is very interesting
You must ensure that you disable auto physics updates or you're gonna get some weird results
So I would have to implement your example in every script that needs some type of physics step?
You would generally write your own entity system
any object you instantiate, you would do it through the custom entity system
I see
thinks like player rotations should also be handled in Update()
otherwise you'll get nasty input lag
As for the entity system, you could just create a new base class called SimulationEntity, or whatever you want
So I'm thinking I would make a system that's higher up in the script execution order that can register some type of "callback"
then have all of your new scripts derive from that
yes, the class system ^ would handle that
I see
On the base entity class, you would have SimulationUpdate()
then you can call it on any entity that derives from it
etc
What would you recommend instead?
also it's interesting that you mentioned this.. Isn't that the network tickrate? I'm curious to know if the custom physics tickrate would matter in this case
Network tickrate and simulation tickrate are both the same. All of their code runs from the same clock in a multiplayer environment.
ah okay
that's why it's not logical for most games to just "up the tickrate" because then you run into bandwidth issues
yeah that makes sense
can I ask some C++ related help here
its a simple question with which I am struggling
@rose streamIf it's unity related, I don't see why not
i am writing a native plugin C++ so i can import it in unity
fire away
Heyy, First time asking for help here, so I hope this is the place to do it. >~<
I'm using a script to spawn random humans, with random meshes and texture. I was able to get the meshes working, but swapping the textures has proven to be a little more difficult.
From what I can tell the correct texture is being applied to the component as a instance ; what I want. But the original material is still there and appears to be overriding the instance texture.
public SkinnedMeshRenderer class1
public Texture Farmer1;
public int skinPicker;
skinPicker = Random.Range(1, 4);
if (skinPicker == 1)
{
class1.material.SetTexture("_MainTex", Farmer1);
print("Skin 1 Applied");
}
Any help would be amazing, i've been looking online for the past 2 hours and I cant work it out.
Kinda looks like you attached two different materials to the object? Not enough context here really
you can create a public texture array and assign the textures in the inspector
navigate through the array with a random number generated each time with time span
in that way
you can do the texture thing as well
also why did you name your renderer "class1"
i think copy paste stuff happening there
there's only one mat assigned before the script adds a second one, would I have to delete the first mat somehow?
Just assign the new one
No idea why you're adding a second one
You have to show your code
!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.
There's actually 3 materials here
Open the materials dropdown that's the only important bit here and you have it hidden
ok i have a question
in C objective you have a statement like char** argv
in which you give pointer to a pointer of a char
like char[][]
or like string[]
would this work in C++
where char** dont work as expected
they simple use char* and assign the value
or sometimes char* argv[]
also if its a char** argv
how can I call it in C#
First of all. Do you really need to go into native?
Because it complicates things 100%
You can use pointers in C# if thats what you're after
char* argv[] is just an array of pointers, and so is char** essentially
i am making use oggvorbis library to encode audio packet into a custom file format
so gotta make use of C++ as C# bitfields are not supported
if they are then I did have to make use of enums and that is a pretty pain
iirc char** can be marshalled as new char[] { 'a', 'b', 'c' }
and if I am to call char** in C#
how would I do that
you would use the byte type
i once used a marshal where I gave only string [] as input and it worked
but forgot how?
actually yeah that's correct, definitely use the byte type (in c#)
byte is 8 bits
where in order to define the header of the ogg packet
you need 8 bits or 1 byte
3 bits for size
4 bits for something i forgot
1 bit for a flag
is there an easy way to make a list "readonly", like anything can see the list and its contents, but are unable to use List.Add() and other methods like that ?
char in c++ is (usually) an 8-bit "character" otherwise known as a byte in c#
What's the problem?
yeah chars in c# are 2 bytes
Yeah don't confuse c++ char with c# char
if taken a look into C++
char holds 8 bits
just make it private, then use a property or function so other things can see it
how am I supposed to take a uint type and convert it to 3 bit uint
like unsigned int i : 3;
bit shifting
i know about bit shifting but I am pretty noob in case of unmanaged memory in C#
better let me be my way
anyways thx for the help
what are the C++ method arguments
"path to ogg file" "loop start points" "loop end points" "path to save the encoded file"
pretty dirty implemented but works the best for me
also wouldnt
fprintf(stderr, "Error: could not open input file\n");
cause unity to crash?
invalid memory accesses will cause unity to silently crash
π₯²
now i get it why unity crashed last time
i thought fprintf is present everywhere
so it wouldnt crash
would this work in android
FILE* infile = fopen(argv[1], "rb");
im fairly certain in this case you need to use the library directly if you want to interop between c#/cpp (so implement the ConvertFSB method using a feature called Platform Invoke.) I have a feeling you maybe want to simply pipe stdin/stdout using https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=net-7.0
let me have a look at it
I am using for android
not pc
otherwise I could simply make use of a command line application working behind
Why don't you just use a library that already handles this for you? Such as https://github.com/SteveLillis/.NET-Ogg-Vorbis-Encoder
i need decoder
with crc32 packets
and raw vorbis packets
header sizes and linked lists
those decoders simply dont reveal that much
Why do you need this exact format?
to create a replica of fsb5 format
like you know
FSBank is supported for windows only
i am trying to write something that replicates it
FMOD Studio only takes input of fsb4 and fsb5 files
in unity fsb5 is the output of every audio file
with compression format vorbis
as vorbis is kindda used everywhere
so anyone can dynamically make a load of .ogg or .wav file and convert it to .fsb5
then make use of it in Fmod studio
my goal is android,linux and mac
If you want to write your own C# bindings for the library, you'll have to first build the C++ library for your target architecture (for example android could be maybe AArch64/ARM64)
And you're using the correct native library for your testing?
yep
ogg and vorbis static android libraries compiled with android studio using jni
not done by me
found on github
Have you thought about writing a test app (in C#) before messing with it in Unity?
yeah it works
but I am going to try it again one more time
dont worry
i will make it open source once its completed
all the code
compiled libraries
unity project and bindings
for both android and pc
then you can have a look
im more concerned about the import settings or whatever it's called
in case of the import setting
you need to clarify the processor
or architecture for which the library is built
if its build for x86 android
then in the architecture type
select x86
make a call and it works
make sure its in different folders and architecture type is defined otherwise unity wont build and generate an error with 2 libraries with same name
okay so if you understand that then my next question is if this (reply) is the error you're having
idk
i think it was due to something else
cuz fprintf is defined already to C++
but as the memory is not given
so it might cause error
but shouldnt as every application even if its GUI
its also command line
gimme 30 minutes so I can finalize things
okay so try debugging by another means. don't print to stderr (maybe stdout) or simply just write to a file using something like std::ofstream
Wait how are you invoking the method in c# first of all
android file system is pretty fucked up
i can just return an integer
the integer would be an enum integer from which I can get the error in C#
not a problem for me
dont mind but let me finalize things first then I will share the link with youπ
Im looking over some of Unity's code for the "new" input system rebinds, they have var partName = default(string);, I understand default(T) is useful when you dont know what default value T might accept (for example, you cant make a int null, or set an Object/class to 0), though is there maybe a micro-performance reason why Unity would choose to use default(string) specifically instead of string.Empty or just "", or is it just a convention/good practice?
object/class is 0
the memory is managed by the CLI
that,s why you cant
@carmine orbit was there anyone answer you yet? I will not call findobjectsss in every update, if the number of gameobjects is static i will call it in awake or start only else i will consider object pool
Well I understand why you cant set a class to 0, cause its not a numeric type, I was more wondering why Unity would choose to use default(string) instead of string.Empty or just "", since in this case "T" is string, and I dont see a reason why someone might want to default a string in this way as oppose to the others
π
from 0 i meant total null
NULL
0
0 mans nothing is allocated
The reason you can't set int to null is because it's a struct, and structs are value-types which apparently can't be null
correct
yep
Null string means you have to allocate a char* for one byte and remember its capacity and size
yea
but in case of unmanaged
you will need Marshal.AllocHgGlobal to do so
So default(string) allocates nothing, and string.Empty and "" would allocate 1 char*?
it just allocates the memory to the class
remember CLI
in C# the memory is managed by the CLI
To answer your question I don't think you need to worry about performance in this case
Well im just curios why a programmer might choose to say var someString = default(string); over just saying var someString = string.Empty; or var someString = "";, if im understanding correctly, the latter two ways allocate some memory, while the first way doesnt allocate at all? Or am I misunderstanding what your saying?
Oh i forgot string in c# is immutable so you probably need a char* and size only
simply put
a string is like a char[][]
arrays always use 1 byte to store their size
even if its size is zero
if it is not used
then the char[][] will be unassigned and the compiler generates an error
you just cant do a string null
but yeah
you can do the null to a pointer as the size of the pointer or stacks is not defined
In C# you can set a string to null, because it's a class (reference type)
O.o
It's basically saying this reference points to nothing. The same as nullptr in cpp iirc
ok leave the topic by saying
performance wont be affected
its eating brain now
ββ is Equivalent to a ptr[0]=0 you need a byte to store this β0β
i think I already told that
Ah ok, I think I understand what you mean now, that convo did help after re-reading it a few times, thanks - it was some Unity code I saw im using as reference for rebinding, so was just curios, though a single byte doesnt sound like something worth micro-optimizing in production anyway
How often do you guys used UnityEvents? I use them pretty prolifically to bind my prefabs together.
memory is something that takes months to understand
took me 6 months to understand how computer memory worked
π thanks for wasting time
Exactly, which means it's a valid string, it's just empty.
who cares about memory when you have garbage collection? π
still you need to learn it
I failed in my exams due to this
i still remember it
I think curiosity is time well spent, you learn something new, so thank you for teaching me something new π
is armaebiv7a simply ARM32
yeah, it's a non-issue essentially
?
garbage collection can be very annoying and also very slow in certain cases
??
I know, I was joking.
Memory should always be in mind.
it doesn't "just collect garbage" it also moves memory around at will whenever it wants to
oh okay sorry π
looks like a dictator
it is π
lol
yep
it did be a pity if someone can tell me is armaebiv7a simply arm32 or arm64
How often do you guys use UnityEvents? I use them pretty prolifically to bind my prefabs together.
never heard about it
_>
anyone guess my age?
To me UnityEvents are just a cool way for Unity to serialize traditional c# events but I don't use them very often
I use them if im building a script for a designer who would find it easier to hook logic through the inspector, though more often I tend to use System.Action or create my own Delegate and hook everything up in OnEnable/OnDisable, respectively
I tend to stay towards the latter as well
I dont see why you would really use it to bind prefabs, I just use it for stuff thats supposed to happen in scene. Like a pressure plate triggering a specific door = unity event. That way I can visually know which door i am selecting
Doing it through regular c# events is kinda weird imo
Yeah I think in terms of performance/usability it's more of a visual thing(able to be serialized in the inspector I believe) but it's essentially the same concept as regular c# events
maybe I'm thinking about UnityAction actually, I think that's literally the same as System.Action
I do find it a little odd that typically youd create a empty UnityEvent class so it can be serialized, and just an empty class in the project seems like a weird concept to me
π€·ββοΈ sometimes things just need to be setup in scene
huh?
its weirder to have my door for example, know about which pressure plate its trying to react to. Or weird to have another system entirely hook things up
if you do something like public UnityEvent gameEvent in a monobehaviour it'll appear in the inspector automatically
Maybe im thinking of something else, or ones that require params, I remember setting up a event for basically turning Physics.XCast into serialized events in the inspector, and had to do something like this to show up
public class SomeScript : Mono
{
public RaycastEvent onRaycastEnter;
}
public class RaycastEvent : UnityEvent {}
I dont really know what the empty class thing meant either now that i read this
I feel like it's a more streamlined SendMessage feature with some added benefits
and drawbacks i think
i still dont get the point of using it to bind prefabs, but it definitely has its uses otherwise
it definitely has its uses yeah, probably just a preference type of thing
UnityEvents have a generic version that allow you to define the input type.
So like public UnityEvent<float> onTickEvent allows you to call any public parameterless function, or any function that takes in a float.
from the inspector
It gives you the same functionality you see with Unity's button or toggle component.
or those TextMeshPro unity events
or regular c# events, just with the added bonus of being able to manipulate it in the inspector
true
it's probably just that they had to make their own custom implementation to add some magic "under the hood" to be able to serialize everything properly in the inspector
Separate question.
Imagine you had collectable drops.
Like money or items or whatever.
Let's say you sort of expect a lot of them on the screen at once.
And when the player gets close, the collectable flies over to them.
Would you give the player some trigger collider that interacts with collectables and tells them to fly to them.
Or would you give each collectable a trigger that waits for the player.
if only the player can pick them up, id go with it maybe on the player
thats a lot less trigger colliders
ya the logic is... having it on the player gives less control, but is more performant
there becomes a point where writing scalable systems is just not worth it
you could make every system as scalable, adjustable, whateverable as possible. But if you wont ever expand on it then no point worrying about it
you could give that same trigger and script to anything else that can pickup items too
wouldn't you still need to give each collectable a collider(trigger) so that the player trigger can detect if it's intersecting with a collectable? or am i misunderstanding
well the collectables need a normal collider so they dont fall through the floor and shit
oh yeah true π
thats what i was assuming too, i imagine there wouldnt be a massive performance hit anywyas unless you have a ton of items on the floor
but at that point, the amount of game objects would be worse than the trigger lol
I think the logical solution would be to have a single trigger on the player then because otherwise you'd need a collider for actual physics collisions and then wouldn't you need a second one (per collectable) that's a trigger? I forget if triggers still have normal collisions or not π
Yes u would need both
The only scenario I can think of for putting the trigger on the object would be if the object is unique, or interacts with anything/anyone.
You wouldnt want your player to have a trigger for items, then another for idk opening a door when you are close
Which is a lot of scenarios I guess, idk why I said only
For example I have a cube which dissolves when the player comes close, it has a trigger on the cube itself. No need for the player to do this behaviour, so the script is on the cube
so wouldn't having both a normal collider and a trigger collider on each collectable item be like O(n) more expensive?
Calling it O(n) sounds weird for number of triggers but yes. Which is why I agree to put it on the player in this case
I mean if the player is chilling on its own physics layer and you just have a bunch of triggers listening for that one collider, it's pretty whatever.
Cost wise.
yeah i thought so too i just couldn't think of a better way of explaining my train of thought lol
If it's one object it doesnt matter what you put it on, but depending on the use case sometimes it makes more sense for it to be on the object or player.
Like a ship opens up when you come near, put it on the ship. Even if theres multiple ships at least they can have their own events and whatnot
You pickup an object by being near, put it on the player. But in this case theres obviously multiple objects.
Even tho both are essentially the same, check if the player is within range
You could theoretically use Physics.SphereCast too but I'm not sure how expensive that is, maybe less such if you're only targetting specific layers but I can only assume it's fairly high compared to having the physics system detect intersections with triggers
Every object on the floor too will basically have the same behaviour. If you want different behaviour it can just inherit from IPickupable (idk maybe name it better) and define it's own implementation
should be roughly the same if its non alloc version
it says 'android.enableR8=false' is deprecated.
i had this error before as well
like a year ago
now i forgot how to fix it
any helps
This would also alleviate the need for 2 colliders(1 normal, one trigger) per collectable. I think...
You'd only need 1 collider per collectable
To give a better idea for the pickup I'm imagining. Think of the XP bits from those Vampire Survivor games.
Lots of them.
These blue crystal thingies.
if you have a choice between maintaining giant amount of in scene colliders, triggers whatever and a simple straight forward solution out of scene graph that is slightly more expensive, chose the latter
treat performance costs as balancing act, is it reasonable to exchange performance for clean architecture?
My opinion: fuck around and find out π
Step 1) Fuck Around
Step 2) Find Out
thats an interesting example
because if you rely on physics for that, youd end up with large amounts of game objects in the graph just to have colliders
that cost can be alleviated with some simple spatial structure, probably
so you dont have to have gameobjects
AABB isn't terribly expensive either if that's a possibility
definitely with that amount of objects
spatial hash would work with maps of any size
especially since they seem to be clustered together so tightly
afaik its not made in unity
so it by default doesnt have associated gameobject/scene graph overhead
but it 100% has acceleration structure
there is no way around it
you would probably need ecs tho for the amount of enemies it has
what do you mean by acceleration structure?
I'm under the impression that ECS could be "the way" to do such a thing, but you could theoretically get by (probably fairly well) with the various techniques mentioned above
any spatial structure that accelerates queries, quad/octree, grid/spatial hash, bvh etc
the pickups yea,
the amount of enemies that vampire survivors has, probably not
actually idk how many enemies it has, ive only seen gameplay briefly where the screen was full
I've never seen the game, but I've seen some very impressive 3d work with ECS so I can only guess
ecs is certainly good pick here, unity one will provide massive performance gains, but if you dont need it, like in case of vampires you can get away by simply looping a list of objects
there arent that much objects, and just looping them will work just fine
they also dont have any advanced ai
so you dont maintain 1000 bts
not even necessary
you can use flow field
one fill of the graph per frame and all enemies know direction to player by sampling direction vector of the cell they are in
almost zero cost per agent
Why every frame. Time slicing it based on the distance to player would be even better
yeah you can tick it, but even every frame it would have small fraction of cost
compared to computing paths
There are a number of optimizations that can be done definitely, the real question is whether they need and/or are willing to implement them
Just want to mention
not making Vampire Survivor game
just gave a sorta extreme example for the number of drops on the ground
something like uuuuh
Enter the Gungeon is probably the best comparison?
Bullet Hell-y
lots of projectiles
fun fact,i work on a bullet haven game also,like vamp s ,brotato,etc.
Personally I would say only optimize when needed, otherwise you're probably wasting your time on something that probably isn't even an issue to begin with
Most modern hardware will be able to cope just fine
It's definitely another story if you're specifically targeting older hardware, but you can only find out one way or another
Can someone help me with the Load Method using System.Runtime.Serialization.Formatters.Binary
I don't know how to display the items.I'm sure that the items are saved because i've looked into the binary file.
So the problem is that the RetriveItemList() is always log (Item list is empty)
(The materials are displayed correctly)
I definitely understand the natural feeling to write "the best, highly optimized"β’οΈ code that will run on a potato, but today most computers can run insanely fast and unless it becomes an issue down the road then just don't worry about it until you need to.
I don't see anywhere in your screenshots that rewards.itemList is ever assigned?
in the RetrieveItemList() function,first photo
That's a local variable in the method that is assigned from rewards.itemList, where is rewards.itemList assigned?
in the Rewards script
where do you populate the rewards.itemList variable
So where is the code that loads the itemList from the file
First image sent,is loading materials(which is working) but cant load the items correctly
I see you do rewards.materials = loadedData.materials; but you never do rewards.itemList = loadedData.itemList in the LoadData() method
private void RetrieveItemList(List<Item> itemList)
RetrieveItemList(loadedData.itemList)
Love you
in the RetrieveItemList method, remove the List<Item> itemList = rewards.itemList; line
it works now?
Y
okay cool
I was trying to help you clean up your code but as long as it works that's great
can't wait to show chat gpt i'm superior 
Hey, how to focus on a folder in unity editor?
var folderObj = AssetDatabase.LoadMainAssetAtPath(Path.Combine(""));
Selection.activeObject = folderObj;
EditorUtility.FocusProjectWindow();
It is OK but I want to go to an empty folder in
in case anybody else had the same question, IReadOnlyCollection<T> was what i was looking for (i think)
What's wrong with the generic IEnumerable<T>? Did I miss something?
IEnumerable<string> test = new List<string>();
I guess it's still writable
Hey, I want to initialize a field after creating a SO just once.
Using OnBeforeSerialize is OK but it does not work for asset duplication.
What about OnAfterDeserialize or OnEnable, Awake,
this code just crashed unity 
Hello, how can I use SetActive in Photon, to hide a object for both players? I tried this way but it gives an error:
GameObject nesne = liste[0];
PhotonView photonView = GetComponent<PhotonView>();
photonView.RPC("gizle", RpcTarget.AllBuffered, nesne)
[PunRPC]
void gizle(GameObject nesne)
{
nesne.SetActive(false);
}```
The error:
``Exception: Write failed. Custom type not found: UnityEngine.GameObject``
I'm sure that "nesne" variable isn't null. I checked it.
you canΒ΄t send custom classes thru Photon. Also #archived-networking
i(t)=i(t-1)*something
=i(0)^(t) and something<1
so i will never reach zero
mhm...
gotcha!
ty
Okey, sorry and thanks!
No worries!
oh i miss read, the correct formula should be:
i(iteration)=i(iteration-1)-i(iteration-1)*something
i(iteration)=i(iteration-1)*(1-something)<= this thing also < 1 and > 0
but the result is still the same, i never reach 0
hello guys im doing an isometric game and i wrote a code to generate tiles based on Perlin noice and i have an issue with the tiles they do not generate in a flat surface its like they have different elevation does anybody know how to fix it https://paste.ofcode.org/Gf74rYbaqSY58v55hnBuU3
Use z instead of y ?
Hey, I got a bit stuck here so I figured I'll ask here and see if I could get some response.
My goal is to have the planet rotate constantly, and affect the ball so it rotates the same speed as the planet. But the catch is I don't want the ball to impact the planet's rotation when it's rolling over the surface of the planet. Any ideas?
its 2d no z
its isometric its flat but has the illusion that its not
So, the gound is z-x ?
Oh, ok nvm I understand.
Do you use a single renderer ?
Because it seem to me that it render group of tiles by group of tiles
(That being said, you might want to find an alternative as performance will tank)
i render them individully because its a small world right now but in the future this must change
So, you are saying it did not help ?
Alright, I do not really know how to fix the issue. However, I am pretty sure this is about rendering order. (And not height)
Maybe try to read: https://docs.unity3d.com/Manual/Tilemap-Isometric.html
okay man thanks a lot
I don't understand what could be wrong, this is supposed to make it so if you hover over a button arrows appear around the button but it isnt working and i dont understand why
How can I recognize the type of specific scriptable object assets in AssetPostprocessor?
AssetDatabase.LoadAssetAtPath ?
HELP. What am I doing wrong? On the line AssetDatabase.AddObjectToAsset(sprite, savedTexture); error
private async void SaveTextures(List<ImagePiece> pieces, PiecesSpritesStorage piecesSpritesStorage)
{
var tasks = new List<UniTask>();
var nPieces = pieces.Count;
for (int i = 0; i < nPieces; i++)
{
var id = piecesSpritesStorage.PiecesCount + i;
var spriteTexture = _imagePieceToSpriteConverter.Convert(pieces[i]);
byte[] spriteData = spriteTexture.EncodeToPNG();
var path = _config.GetSavePieceTexturePath(id);
var task = UniTask.RunOnThreadPool(() => File.WriteAllBytes(path, spriteData))
.ContinueWith(() =>
{
AssetDatabase.Refresh();
ReimportAsSprite(path);
AssetDatabase.Refresh();
Texture2D savedTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
var sprite = Sprite.Create(savedTexture,
new Rect(0, 0, savedTexture.width, savedTexture.height),
Vector2.one * 0.5f, 100, 1, SpriteMeshType.FullRect, Vector4.zero,
generateFallbackPhysicsShape: true);
AssetDatabase.AddObjectToAsset(sprite, savedTexture);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(savedTexture));
AssetDatabase.Refresh();
Object.DestroyImmediate(savedTexture);
});
tasks.Add(task);
}
await UniTask.WhenAll(tasks);
}
@strong condor Don't cross-post. !collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
I have a scriptable object in my project. I included it into an assetbundle and also had a reference to it in a scene, and 2 instances of it were created after the game starts
I wonder if anyone knows one of these things:
- How to prevent
textInfo.lineCountfrom being0, whentextisstringEmpty. So it should always be 1 - How to get
TMP_LineInfoandTMP_CharacterInfoeven whentextInfo.lineCount == 0
Because you have it in the assetbundle and you have it in a scene. (Usually, you also bundle your scene)
I'm just using the asset bundle as a way to force load some of my assets
What do you mean ? Because if you have a reference in a scene and in an asset bundle it will definitly be duplicated.
Maybe there is something else you can do ?
Hmmm
Instead of using AssetBundle (If you dont want)
I mean, what is your issue.
I might know something
If I don't use Asset Bundle then it may not have been loaded when I need it
Depends
Asset Bundle is the surest way to do it.
You could, by example. Do Resource.Load(); https://docs.unity3d.com/ScriptReference/Resources.Load.html
My personal problem with Resource is that it requires me to place all the assets that has to be loaded in a certain foler
folder
You can have multiple Resource Folder
I'm well aware of that
They are the assets that I need anytime
Not an issue with Resource
I'm not saying that you should, I'm just presenting alternative.
- Bundle your Scene
- Remove your Reference from your Scene
- Remove the Asset from the Bundle
- Use Resources
Thanks
You cannot have at the same time, a reference to a SO in the scene (Not Bundled) and a reference to the same SO in an AssetBundle without duplicate.
Probably I should make something that I can drag my SO in and store its name
Thanks

I have been working on procedurally generating a large world using Unity terrains. Most things are working successful except terrain stitching. It works for the most part, but in some cases (typically on higher heights) the terrain will not snap together and ends up folding. I am looping through heightmap values and connecting the first row of the new terrain to the last row of the top terrain and the first column of a new terrain to the last column of the left terrain. What I had found was it seems like after about 40m in height, the snapping starts. I added some controls to clamp the heights (not 100% working yet), but I can't fathom that this is the solution. There has to be terrains that have been developed before with wider height gaps. What am I missing here? Is it just not possible?
(Please ignore the ugliness as this is just solid color materials currently and no refined procedural noise)
public void groundCheck()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, groundcheckDistance, ground))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
For some reason this not detecting my ground layer when on the layer, if i change the distance to around 5 it detects the layer but when i jump it detects the layer for too long allowing like 10-15 jumps
What is ground?
I need some help regarding transform.LookAt.I basically have a planetary system with orbits and then the player would be in a sector in that system and the code is supposed to find where the stars / planets are in relation to the sector and display them as a sort of "physicalized skybox"
however, sometimes this fails and projects the planet and star at completely false positions
{
_planetCParents[i].transform.rotation = Quaternion.LookRotation((GlobalManager.Instance.CSSI._celestialBodies[i].transform.position - transform.position), transform.up);
//_planetCParents[i].transform.rotation = _rotationObj.transform.rotation;
_planetCObjs[i].transform.localPosition = new Vector3(_planetCObjs[i].transform.localPosition.x, _planetCObjs[i].transform.localPosition.y, Vector3.Magnitude(transform.position - GlobalManager.Instance.CSSI._celestialBodies[i].transform.position) * 1000 + 10000);
}
this is the relevant code (ignore the second line, that's commented out cause it's a relic from an attempted fix that didn't work)
Depending where your transform.position is, you could be starting your raycast under the terrain.
I've seen people using sphere cast in the past to circumvent this
the code points an object (_planetCParents[i]) at the relevant planet ([GlobalManager.Instance.CSSI._celestialBodies[i]) by subtracting that planet's position minus the sector's position, then use transform.LookAt on that
it does work fine usually
but eventually it breaks for whatever reason
the script is on my player model and thats def above the terrain
i could try a sphere cast but every other raycast type ive tried has this issue
Unity use a combination of raycast and spherecast on their character controller.
If you want to learn from them I can provide a link to their code for it?
thanks if you could thatd be great
Can you ask your question please
thanks
do not cross post, you already asked in another channel
If you search for CheckCollisionBelow you'll see what they do
in the onother chanel i dont know the wrong
a*
before this gets buried does anyone know what the solution could be?
cause I'm more or less pulling my hair out cause I don't know what the problem is in the first place / what exactly causes the behaviour)
Help
ok by
how do i make shader code work in URP?
i put it on a material and it doesnt work at all
makes the material invis
oh thanks
Is there a better way of doing this? It feels pretty verbose but I can't find anything else that works in a similar way
[System.Serializable]
public struct Message
{
public float Speed;
public float GetSpeed => Speed == 0 ? DEFAULTSPEED : Speed;
}
const float DEFAULT_SPEED = 0.025f;```
I want to make it so:
The struct has a default value for Speed
If Speed is changed in the inspector then that value is used instead
Like each variable now uses up 3 lines for itself, the property and the const
public float GetSpeed => Speed == 0 ? DEFAULT_SPEED : Speed;
public float GetPuncMult => PunctuationMult == 0 ? DEFAULT_PUNC_MULT : PunctuationMult;
public string GetAudioClip => string.IsNullOrWhiteSpace(AudioClip) ? DEFAULT_AUDIO : AudioClip;```
Getting long. Not a big deal but I'm always trying to write the best code possible
I get an error when I do that, one sec
Yeah it asks me to make a contructor, so I do that and assign values. Then I get a different error about not being allowed have instance property or field initializers in structs
yep that's not allowed until c# 10 which unity probably won't support until sometime next year at the earliest
oh yeah I was actually just reading that
Alright so this is the best way until then?
Yeah alright I'll try that
make struct serializator
private readonly float _defaultSpeed = .025f;
[System.Serializable]
public struct Message
{
public float Speed;
public Message(float Speed = _defaultSpeed)
{
this.Speed = Speed;
}
public float GetSpeed => Speed;
}
That seems even more verbose
public Message(float Speed = _defaultSpeed)
well that's not valid
no errors π€
I don't think so
default parameters have to be compile time constants, not just readonly and/or static. sure they could make it a constant but unity isn't going to be calling the parameterized constructor for the struct so it doesn't matter anyway. and you cannot define a parameterless ctor on a struct until c# 10
sure that is valid. but simply using a readonly field from the containing object isn't
Mine is 3 lines per variable. Yours is also 3 lines + a constructor
Yeah true I guess, what's the benefits of that anyway
I'll only be assigning stuff in the inspector btw
class just seems more appropriate for that, then
so u say: "less code - better"
!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.
formatting
did I just mess up the cs part or something else?
So I tried making movement for my player. When I move right the code does exactly what I want, the speed caps out at MaxSpeed but when I move left the players velocity doesn't stop at maxSpeed and I really can't figure out why that happens. Thanks in advance!
private void Update(){
horizontal = Input.GetAxisRaw("Horizontal");
}``````cs
private void FixedUpdate(){
Debug.Log(rb.velocity.x);
if (rb.velocity.x >= maxSpeed){
rb.AddForce(new Vector2(horizontal * speed* (-0.1f), 0f), ForceMode2D.Impulse);
}
else{
rb.AddForce(new Vector2(horizontal*speed, 0f), ForceMode2D.Impulse);
}
}```
better?
perfect
How can I recognize the type of specific scriptable object assets in AssetPostprocessor?
AssetDatabase.LoadAssetAtPath ?
Should I get all assets and check them?
of course, I does not stop, it should move in other direction 10 times slower
maybe you should consider using this?
if (Mathf.Abs(rb.velocity.x) > maxSpeed)
Mathf.Abs returns absolute value of float
If max speed is the max speed so is valid you probably can lose the =
velocity can be both e.g. -200f and 200f, so Mathf.Abs always returns 200f
https://docs.unity3d.com/ScriptReference/Mathf.Abs.html
and I should add another if that checks if the velocity is positive or negative so it multiplies it by either -0.1 or 0.1
why should you? What do you even need to achieve?
yeah, maybe, doesn't matter so much though
basically I want the player to have an acceleration rate (speed) and the max speed it can reach (maxSpeed) and I don't want the player to loose all the momentum at once when the person stops pressing the direction keys
This code now works great!
private void FixedUpdate(){
Debug.Log(rb.velocity.x);
if (Mathf.Abs(rb.velocity.x) >= maxSpeed){
if (rb.velocity.x > 0){
rb.AddForce(new Vector2(horizontal * speed * (-0.1f), 0f), ForceMode2D.Impulse);
}
else{
rb.AddForce(new Vector2(horizontal * speed * 0.1f, 0f), ForceMode2D.Impulse);
}
}
else{
rb.AddForce(new Vector2(horizontal*speed, 0f), ForceMode2D.Impulse);
}
}```
then you probably need to AddForce to player if their speed is still lower than maxSpeed (otherwise player's speed should be set to maxSpeed) and clamp their velocity
I didn't like the look of just setting the velocity to MaxSpeed so I did it the way shown above
private void FixedUpdate()
{
Vector2 force = new Vector2(horizontal * speed, 0f);
if (Mathf.Abs(rb.velocity.x) < maxSpeed)
rb.AddForce(force, ForceMode2D.Force);
rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);
}
that's not what I mean
see in the example provided
I hope that works
I get this error
oh, no, forget
yes, never mind, we do not need this, because we use Math.Clamp already
ahh, my bad, didnt see that
Now that I got it to work this works absolutely perfectly! Thank you very much
nice to hear, and that error was because you needed to set Rigidbody2D = new Vector(smth, smth), not its x or y values, my bad
Now my basic player controller is done! Now I move onto harder stuff lol
is it ok to have Reference type in a struct? how do I deal with storing a copy of the object
copies of the struct will contain the same reference
If I make it null inside one of the struct will it affect the other structs?
no
ok ty
only copies of that instance of the struct will also contain null in the variable
perfect thx π
This is a bit weird but is there a way to assign a variable from another class in the inspector? Or a way to write down the variable name as a string then at runtime find that variable based on the string?
I'm working on NPC logic and I'm trying to figure out ways to avoid making a unique script every time I want an NPC with different triggers/logic
I want NPCs to be able to check say whether the player is grounded. Or how high a timer on a manager is. Or other various things like that
Is this possible?
when you copy the struct you just copy the reference (pointer) but the memory address pointed wont be copyed
sounds like design problem
you want to check some "value" of some object in run time then you must reference to that object unless that "value" is reference type then you copy the reference
Ok so like if I did it the slow way then I could end up with like 50 scripts:
NPC 1:
if (Player.Grounded)
PlayDialogue("Ground")
NPC 2:
if (TimeManager.Time > 5)
PlayDialogue("Its Time")
NPC 3:
if (TimeManager.Time > 10 && Player.Health > 2)
PlayDialogue("Its Also Time")
NPC 4:
if (Player.Dead || BoxCast(...).collider != null)
PlayDialogue("Fourth")
Like for almost every NPC I make it's a new script which sure is fine but if it can be avoided I'll jump at the chance
can someone help me create a game?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
did you read the bot message
i did
you clearly did not, or you wouldn't be asking if people would work on your game for free
i just dont know which one to click on/use
i will consider having a abstract parent class and has a static references to those objects needed to be checked and some static functions for checking those objects then for the scripts of each type of enemy just pick up the functions on base class they needed
or even a global system that perform logic for each npc based on their type
if you have a specific question about something then you can use #πβfind-a-channel to find a relevant channel to ask the question in. just be sure to read #854851968446365696 and #πβcode-of-conduct first.
if your question is just "can someone work on this with me" then read the bot's message again very carefully
This is a no-go is it?
private void OnValidate()
{
gameObject.layer = LayerMask.NameToLayer("Interactable");
}```
SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (Square: OnLayersChanged)```
