#archived-code-general
1 messages · Page 30 of 1
Your OnTile function, just wondering where this is called from, I guess one single class, not on a tile but on an empty object, right?
Is there a way to make GUILayout.Button prevent clicking stuff below the button?
Hey @plucky inlet I just wanted to thank you for your help yesterday, I tried everything and it didn't work so I'm going to pixelate the model shader wise and then see if that makes some difference, anyway I didn't even thank you so I wanted to thank you now!
its being called from my player script if that helps ahaha
not entirely sure what a single class is..
yeah, and that is only once in your scene, so thats fine
Yeah that still doesn't work. I've tried that already
Oh you didnt? thought you did, and you are very welcome, interesting topic on your side I never touched, so it was a learning for me too 🙂
Damn that looks cool
thanks. Its actually a remake of a game, thought it would be a fun project just for some practice, and im already learning alot. The original game is called "A dance of fire and ice".. an excellent rhythm game!
So i thought id try and make a rhythm game in the style
Nice
Nah there is too many limitation on the render texture for it to be used alone 🥲, so I'll write a pixelation shader, that will give me more control over what is displayed, if I succeed I'll show what I have done in showcase or whatever channel you can display your work on 😉
Whenever I try to open any windows in unity, it doesn't open. I'm trying to open preferences, but after countless attempts it still doesn't do anything when I click on it. None of the other windows open either. I've tried closing and opening unity, and resetting my layout, and it still doesn't work. This problem only occurs on my laptop (which I'm using right now) but not on my PC for some reason. Any help would be appreciated.
Did you try another editor version? just to be sure it happens not in general?
Do you have them detached by any chance? And they just open somewhere else on the screen.
I speak out of experience when it comes to losing an application window for half a day since it decides to open out of view
I’ve looked and couldn’t find the window, and also wouldn’t resetting layout fix that?
Probably
are you using source control with your project
Yea
@compact verge have you ever, in all of history, opened unity hub or unity as an administrator (if you're using windows) or using sudo on a mac?
No but I’ll try that when I get home
no you shouldn't
it is very bad to do that
it will really break things
Oh
hello, I have a problem with sound delay and cant seem to fix it even with the trouble shoot page
my sounds play like 0.1 sec late
is there any way to fix this?
Do your sounds have an empty noiseless space in the beginning?
nope
they sound just fine in the player
its just when i use them in game that they take a tiny but noticeable bit to play
when you press play, the sound noise plays right away in the player?
no
i have it so it plays when a key is pressed
i play it inside a if (input.getkeydown())
Which loop runs that if?
update
and the play sound instruction is also inside that update loop?
can you share the code?
Can you share the audio manager code? use `cs formatting, not a screenshot
start with 3 `, add cs, follow up with your code and end with 3 again
sorry
it's `, not '
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public static AudioManager instance;
void Awake(){
instance = this;
}
public void PlaySound(AudioClip clip){
AudioSource.PlayClipAtPoint(clip, transform.position);
}
}
It's possible your sound clip itself has a small delay at the start
he said no. I tried that too
when i inspect it it doesnt have one
share the sound wave picture
ok
Also TIL https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html exists, that's super convenient
i think thats what im doing
you are
It's great for prototyping or maybe even production mobile
your asset settings are wrong
it's in the docs
there's a lot of nuance in setting up an audio asset
ill try again
then
ive tried every combination and it still doesnt work
and i think in the docs it says that settings only affect the first time played
ok 1500 fps
just an empty scene
it wasnt working in my main project so i did a test one
but still
does the mathf.perlinnoise have some kind of seed? or will it give me the same outputs every time when i input the same numbers?
i think i fixed it but i dont know why it didnt work the first time i tried it
and its also not in the docs
i changed the buffer to best performance
thx for the help
Can anybody give me tips on how to implement map "lenses" or "modes". Those that exist in Civ and Victoria for example.
I could not find any resources regarding that topic.
Do you simply assign a new material to every object or is there a simpler way?
you can try
most games use an ubershader / ubermaterial and toggle things on and off for the sake of simplicity
using an ubermaterial isn't necessarily giving you better performance. for example, some effects require transparency - depending on your scene, rendering everything with transparency support will perform worse than rendering most opaque things opaque
always the same - there is no randomness involved in the PerlinNoise function
I think I understand a bit better now 👌
I am very new to shaders, so I didn't consider combining different functionalities into one shader
Hello there! Could someone explain what kind of shader is it (I mean while transition between wagons) ? https://youtu.be/ew4jsFJS5uY
Last Survivor : Zombie Game Android Gameplay - Gameplay Walkthrough Part 1 Tutorial Zombie Army Train Defense Game (iOS, Android)
Last Survivor : Zombie Game - Suup Games
👍Join And Become My YouTube Member https://www.youtube.com/channel/UCRf4-iCB2SXg9OsuFauzlsw/join
🔔Please Subscribe:
Pryszard Gaming https://www.youtube.com/channel/UCRf4-iCB2...
@plain moon You mean the way the roof disappears? There are a thousand different way to make something like that. Goole dissolve shader
Yep 😄
hey guys, i have problems with a little rocket simulator i am making. I am trying to rotate the rocket based on input, and it works fine when rotating counter-clockwise but not when rotating clockwise. it is as if the rocket tries to smoothly clamp on 90 degrees. also when rotating counter clockwise, it rotates faster at the 90 degrees point
Code:
void FixedUpdate()
{
rb = currentRocket.transform.GetComponent<Rigidbody2D>();
rb.mass = currentRocket.getTotalMassOfRocket();
CenterOfMass.transform.localPosition = currentRocket.getCenterOfMass();
if (canControllRocket())
{
rb.AddForceAtPosition(currentRocket.totalAccelerationForce * Throttle, CenterOfMass.transform.position);
rb.AddTorque(-rotF * currentRocket.totalRawAccelerationForce * Throttle * 0.005f, ForceMode2D.Impulse);
}
}
I don't see anything in here reading input
it's also.. quite hard to read, as your code is quite verbose
would recommend adding some intermediate variables in there
Still don't see anything in here that deals with input
input is recieved like this:
if (Input.GetKey(KeyCode.LeftShift))
Throttle = Mathf.Min(Throttle + 0.005f, 1);
if (Input.GetKey(KeyCode.LeftControl))
Throttle = Mathf.Max(Throttle - 0.005f, 0);
float RotL = 0;
float RotR = 0;
rotF = 0;
if(Input.GetKey(KeyCode.A)) RotL = -1;
if(Input.GetKey(KeyCode.D)) RotR = 1;
rotF = RotL + RotR;
let me check something
nvm, nothing found
the value in rb.AddTorque() doesnt change, i thought that was the problem
Shouldn’t you be multiplying the rotation by a quaternion?
what rotation? i am dealing with Torque, not transform.rotation
Yeah I see that now
ima crosspost in #⚛️┃physics
When applying torque either as a force or an impulse, you can use any value to get the required change in angularVelocity. However, if you require a specific change in degrees, then you must first convert the torque value into radians by multiplying with Mathf.Deg2Rad then multiplying by the inertia.
Wouldn’t this be it?
adding torque results in a change to rotational velocity
not a "specific change in degrees"
That answer sounds AI-generated
Lol it’s from the unity manual
even my confusion is confused, idk what to do
maybe its conflicting with rb.AddForceAtPosition() ?
I assume you want the physics to be taken in account for your rotation?
If that's the case you could just add a force at the base of your rocket, and depending on whether you want it to steer right or left, that force would be negative or positive
That way the physics will be taken in account and your rocket will tilt right or left depends on the sign of the force
solution was found in #⚛️┃physics , still need help there if you may
How can I find the Camera.main in another scene? (I am writing a server that has multiple scenes loaded and I want to find the main camera of the player that requested something)
Camera.main does not give a lick about scenes
it just finds a GameObject (in any scene) with the MainCamera tag and a Camera component
I have a code related question, how does one functional in unity?
What does that even mean?
functional? 🤔
Correct. A paradigm
In Javascript, I typically write in functions. But I wanted to know if unity has some functional friendly coding, if not, it's fine
Plus I am absolutely new >.<'
Unity uses C#
A derivative I was told
It's C#
From a Discord that led me here, some members expressed certain aspects of Unity C# isn't the same as .NET C#
Notably constructors are different in terms of retrieving any value?
your sentence structure is incorrect, that's why the confusion. unity uses the c# language which is similar in most aspects to javascript, but it's not a derivative or unity specific. there are certain aspects that are different, like constructors, but that is only for classes derived from a MonoBehaviour (a unity-defined class); it does not affect how they work in a regular c# class . . .
Yeah, you worded it better
The latter portion, I also apologize for not being clear or specific upon entry x.x
But thank you for the clarification, I'll probably see if there's any good tutorials to get me started, thank you guys for your time!
There are some pinned in #💻┃code-beginner
And general Unity ones pinned in #💻┃unity-talk
How would I go about using an object pool for vfxgraph objects? How can I know when they are done playing and can return to the pool?
Any good name for a class that contains data or assets and who's role is to provide requesting classes with the data/assets, with minimal logic.
E.g. my most recent need is a class that maps the gameobject layers internally to some enum so requesting classes can request layers/build a layermask dynamically based on enum values. Basically it provides layers info and does nothing else other than some internal mapping and some minor arithmetic to return layermasks.
Every time I end up with a dumb name like LayersHelper or LayersUtils or something along those lines. I was hoping someone who ran into a similar use case had a better name?
I think this is a #✨┃vfx-and-particles question. And as far as my research went, that wasn't practical there is a lot of overhead for a VFX component. What I made was a world wide VFX graph with the limit of particles set to millions, and made it so you could call a particular VFX i.e. Fireball or Explosion in that graph on a position in the world. That way I could have tens of thousands of fireballs in a single VFX graph. But maybe the #✨┃vfx-and-particles people can help you more with that, I just did it for fun.
Hey guys, I'm doing some profiling of my game... Trying to figure out what the colors in the profiler correspond to. Specifically, why does the "Scripts" category get two colors?
The faded out blue corresponds to the whole script loop. Since you selected the ScriptRunBehaviourUpdate element in the list, that took 34% of the time in average, it is displayed in the graph as bright blue so you visualize how much of the total time it took
Ah, got it. That makes sense.
how to clamp my turret X position ?
This isn't working :\
float degreesPerSecond = 90 * Time.deltaTime;
Vector3 direction = target.transform.position - myne.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(direction);
Mathf.Clamp(targetRotation.x, -45, 45);
myne.transform.rotation = Quaternion.RotateTowards(myne.transform.rotation, targetRotation, degreesPerSecond);```
Mathf.Clamp has a return you need to use since the float is a value type
targetRotation.x = Mathf.Clamp(targetRotation.x, -45, 45);
Clamp does not clamp the value you pass to it (in place), it returns a new one
I see, so I need targetRotation.x = Mathf.Clamp(targetRotation.x, -45, 45); ?
yup
Still not working unfortunately , what am I missing ?
You are clamping the quaternion, that goes from 0 to 1
Oh..
I can't directly change myne.transform.rotation.x
How would I insert this clamp in between ?
Janky way is go from Quaternion to Euler, Clamp, and use the EulerAngles, or convert back to quaternion again for your rotatetowards.
To actually clamp the Quaternion, you would probably need to use .Angle and some quaternion math with that. I'm no expert in this to be honest. I would think there is some info on google about this.
Ahh and so I'm back to the same results from last night's searches
The Slerp part seems janky to me at the end.
can't believe it's this difficult to make a turret camera with limited angles :p
Quaternions man...
Quaternion math is a field in itself 😛
But I would expect his code to work to be honest, seems valid to me.
The chosen answer in the thread ? I think I tried that last night, will try again with fresh mind
Yeah, just remove the Slerp and use your RotateTowards, also remove the .z = 0 if you don't need that part.
Well I guess it just wants to do it's own thing
float degreesPerSecond = 90 * Time.deltaTime;
Vector3 direction = target.transform.position - myne.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(direction);
Vector3 look = target.transform.position - myne.transform.position;
look.z = 0;
Quaternion q = Quaternion.LookRotation(look);
if (Quaternion.Angle(q, baseRotation) <= 45)
targetRotation = q;
myne.transform.rotation = Quaternion.RotateTowards(myne.transform.rotation, targetRotation, degreesPerSecond);```
It looks like you are clamping nothing. I believe it should be like... float f = Mathf.Clamp(targetRotation.x,-45,45);
And then use that float when setting your rotation.
the problem I'm having is creating that new rotation and setting that float somewhere in the Rotate Towards 😵💫
Works for me.
you're definitely worrying way too much about euler angles here. Use gizmos and visualize the rotation/direction its facing in 3D.
Tbh I have no clue how to start debugging rotations
like this
I mean it does follow my player, it just completely ignores the clamp :\
I have never had to set a quaternion angle. Too complex for me. I have only used Euler angles.
First put the arrows in Pivot / Local mode. They will show the local rotation, now it's the global one
I usually use LookAt but never had to clamp X axis within a range before :\
if this is the code I don't see any clamp here
#archived-code-general message
They said this works
Local mode
using UnityEngine;
using System.Collections;
public class Tracker : MonoBehaviour
{
public Transform target;
public float maxAngle = 35.0f;
private Quaternion baseRotation;
private Quaternion targetRotation;
void Start()
{
baseRotation = transform.rotation;
}
void Update()
{
Vector3 look = target.transform.position - transform.position;
Quaternion q = Quaternion.LookRotation(look);
if (Quaternion.Angle(q, baseRotation) <= maxAngle)
targetRotation = q;
transform.rotation = targetRotation;
}
}
This is my code, that made the GIF of the turret following the box.
clamps in the sense that it won't go past a certain delta but it also wont likely reach its actual limits
Yeah that's fair enough, it completely stops rotating outside of the maxAngle range.
But a camera wouldn't know anything outside of its range anyhow.
now it doesn't move at all for me 😅 copied this exact
except I only set a diff transform
Vector3 look = target.transform.position - myne.transform.position;
Quaternion q = Quaternion.LookRotation(look);
if (Quaternion.Angle(q, baseRotation) <= maxAngle)
targetRotation = q;
myne.transform.rotation = targetRotation;```
what is this black magic fuckery
Well, can't help much more then I already did. 🤷♂️
You can see what it does for me, and you have the code. I don't know why you changed myne, but I would have just expected that the Quaternion.Angle is out of range already, then it doesn't move at all. So increase it from 35 to something else.
I changed to myne because the script is on a parent object and don't want to rotate the parent
wait it does work.
it only rotates when I'm within 45 tho
baseRotation = transform.rotation; did you also change the baseRotation with myne then?
that means in all directions too not just X
if (Quaternion.Angle(q, baseRotation) <= maxAngle)
targetRotation = q;
else
targetRotation = Quaternion.RotateTowards(baseRotation, q, 45);```
and yes this whole approach is flawed
you should do this with pitch and yaw angles
as float variables
clamp those
and drive the rotation with them
It sounds simpler this way but have no Idea what methods to look into, time to google then I guess
Wait.... I think this is working..
Actually pretty sure all these 4 lines of code can be cut down to:
targetRotation = Quaternion.RotateTowards(baseRotation, q, 45);
That's quite an clever way to clamp it to 45 degrees, never seen that before.
yay! thanks. It's not perfect and will have to fix that snapping when underneath it , but I can work with that probably with rays or Dot product
better than collapsing onto itself like before
some gimbal lock / roll going on too
might want to provide the second parameter to Quaternion.LookRotation if you aren't already.
the upwards parameter?
Will do some more testing and try to tune this . thanks for the help everyone!
did you consider using constraints to achieve this?
for example, you can add an AimConstraint to your security camera game object, then create a transform that it follows. limit the position of the transform such that the camera doesn't exceed its arted rotations, which is much simpler
right now it looks like you've reinvented AimConstraint
the multi-aim constraint component supports clamped rotation explicitly - https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.2/manual/constraints/MultiAimConstraint.html
whats the name of global gbuffer textures on urp?
if I plan to go back to a scene later do I need to unload it?
running into random bug where my character isn't starting at the location hes supposed to when a scene is loaded
and not sure why
SceneManager.sceneLoaded += LoadState;```
```cs
public void LoadState(Scene s, LoadSceneMode mode)
{
player.transform.position = new Vector3(0,0,0);
}
When the scene is loaded...however that isn't happening (he spawned at like 5,-3 last time)
its almost like when built on mobile it isn't re-loading the scene...and thus not teleporting him back to 0,0,0
(aka go to scene1, then mainmenu, drop down to like -5y in main menu, go back to scene1 and he doesn't tp to 0,0,0)
this only happens on the apk and not inside of the play in unity which is why Im confused mostly lol
Any splitscreen parallax techniques other than duplicating background objects and culling per-cam?
Lets say I have a list of 10,000 object and a set of 30 conditions which I need to check. Is it better performance-wise to:
A. Loop through each object once and check all 30 conditions in each loop, applying the appropriate functions per condition
or
B. Check the condition, and if it is met, loop through all 10,000 objects and apply the appropriate condition function
or
C. They are the same
My initial instinct is A, because it is far fewer condition checks (30 instead of 300,000) However, part of me thinks that looping over 10,000 objects 30 separate times would be slower
what ar eyou actually trying to do
D. Figure out a clever way to avoid doing that much work in the first place.
I'm not sure how to describe that without making it more confusing
🤔
Does anyone know how to search a project by tag? I have a tag that keeps reappearing and it's not in a scene, I think it's on a prefab but having a hard time hunting it down.
wdym by "a tag that keeps reappearing"?
how and when do tags "appear"?
what are you trying to do lol
just be succinct
what is the game/app and what part is this?
Bump
The game is called Roll, you can buy and create dice, up to about 10,000 at once. Everytime you roll your dice, all 10,000 need to calculate their new value. The value can be increased by passive abilities which will usually multiply the value of all dice by some constant. So I am trying to apply these passive bonuses to all dice when they are rolled.
I can clear the tags from the TagManager but they will come back when I reopen the project. Aka there are assets in the project still using the tag I'm trying to remove.
does the user visualize each individual dice?
yes
What is the tag? It could be a plugin adding it.
okay well it's sort of obvious to me that you don't have to roll each individual dice...
like i understand from the point of view of some starchiness that that makes sense
?
The dice can all have different faces, one die might be your standard 1,2,3,4,5,6 but another die can have faces that do other things
are the dice rolled in order?
It's my own tag called "Deflect". It's something I was using on rocks and hard objects to have the player's sword deflect when striking. I found the prefab by searching one at a time but it would be nifty if you could search the project assets by tag. Seems you can only do it within an open scene.
in other words, can something about the result of dice N affect dice N-1?
yes
are their effects always commutative? so are there any dice where (DICE TYPE A ROLL) . (DICE TYPE B ROLL) would not have the same result as (DICE TYPE B ROLL) . (DICE TYPE A ROLL) ?
for example, a dice that says "multiply your score by the side this lands on" is commutative. a dice that says "multiply your score so far by the side this lands on" is not
it sounds like you've basically made https://www.youtube.com/watch?v=6DORG3uIoH4 as a game (a parody of sushi go)
In this game tutorial, you'll learn how to play the gameless board game "Sushi Go!"
Buy Sushi Go!: https://amzn.to/2H92EzZ
Please consider supporting me on Patreon: https://www.patreon.com/TheDragonsTomb
Get your very own "Cards. Deal With It" t-shirt here: https://teespring.com/stores/the-dragons-tomb
Follow The Dragon's Tomb on social med...
Well it goes in rounds, there are fast effects which all happen at the start of the roll, then slow effects which go based off those results, and then slowest effects which go after everything
okay well
i think you should do whatever, because iterating through 10,000 items doesn't matter
a computer iterates through 10,000 things very quickly.
if your profiler starts to say that something matters, you know, then you can deal with it
just focus on making a fun game
I have had optimization issues in the past
well
so I wanted to see if there was a clear answer here
but yeah its kind of like if sushi go had 100's of different cards
someone sent me this meme today where it's daffy duck counting money with the heading, "asking a senior developer 4 questions and getting the answer 'it depends' each time"
that's you
there's a really high level way to optimize this, but it may exceed your math abilities, and it may constrain your design space in a way that is not fun
nobody wants to do math for fun
so theres not 1 thats inherently better?
for
if
if
if
vs
if
for
if
for
if
for
for example, if i had 10,000 six sided dice, and you asked me to roll all of them, i wouldn't call math.random 10,000 times
in my experience, when people ask about these sorts of micro optimizations in the abstract
they have performance problems due to colossal flaws in their code, which they don't share
but thats like the whole point
Im sure there are many flaws, but i was just wanting to know if one way was better than the other, seems like the difference is probably negligible
okay, but do you see that there is a very optimal way to do the implementation for
? RollNDice(int sides, int numberOfDice) {
...
}
like that function can be implemented in O(sides) instead of O(numberOfDice)
and
int RollNDiceAndReturnSum(int sides, int numberOfDice) {
...
}
is O(1)
yeah but the die faces can be weighted and such to skew the result to your advantage
okay, you're basically answering every question with "It depends," you don't need me to go through the "it depends" thread
you're totally capable of figuring this out yourself 🙂
go out there and make the game
i mean the game is made, just working on an update
trying to bring it to mobile
and afaik optimization is quite strict on mobile platforms
and yeah, thats why i was just trying to ask the high level question instead of going into the details...
you must already know that
for(var i = 0; i < N; i++) {
Method1();
Method2();
}
will execute the same number of steps as
for(var i = 0; i < N; i++) {
Method1();
}
for(var i = 0; i < N; i++) {
Method2();
}
as long as Method1 and Method2's effects are commutative
so they're the same
it doesn't matter if it's an if statement. you must know that
the essential part is if they're commutative
you didn't miss anything here
your profiler isn't pointing any of this out
so i guess come back with a specific question instead of a high level one
ok thanks
do you think you can implement this in O(sides) ?
? RollNDice(int sides, int numberOfDice) {
...
}
i think this is the first exercise you need to do
doesn't seem possible with my current implementation
i want you to step back and think what i am asking. in isolation, without any thought to what you have written so far
if i fill in ? i am going to give away the insight you need to have
on this journey
so do you see how you can do it or no?
what if i asked you to flip N coins?
can you do that in O(1)?
just take a random number of coins from total and assign tails?
Im not sure what the function is trying to achieve
i think answering these questions is all part of the journey
to learning how to optimize your game
what does that concretely mean?
here's a question i dont' think gives anything away. if i ask you to flip 1,000 coins, about how many will be heads?
If all you want to know is how many of 'numberOfCoins' will be tails and how many will be heads, you can just say
tails = rand(0,numberOfCoins)
heads = numberOfCoins - tails
try answering the question just before this message to see why this response is wrong
so what do you think?
if i ask you to flip 1,000 coins, about how many will be heads?
I though it was "heads = numberOfCoins - tails"
Hey! Could someone please help me fix a code like this to interpolate a sprite(or any object)'s alpha color from 0 to 255 when the player gets close?
float MinDist = 5f;
void Update () {
if(Vector3.Distance(transform.position,Player.position) <= MinDist){
*Colorlerp code goes here*
}
}```
just use your gut intuition
like in real life
if you flipped 1,000 coins
about how many will come up heads
500
Trying to create a box of tutorial text on a wall that is only visible when approaching
lmao
okay.
so clearly tails = rand(0, numberOfCoins) is wrong
how did you figure 500 was the right answer?
its odds*trials
okay so
Bump agaim 😂
there must be some way to still incorporate random right? like the method isn't
int ExpectedHeads(int numCoinFlips)
it's
int Heads(int numCoinFlips)
so on this journey
to optimize your game
if you truly want to optimize it
you have to be able to give me a random number of heads in O(1) time, that is at least correct
@tiny orbit is this helpful?
@tiny orbit do you see why tails = rand(0, numberOfCoins) is wrong?
yeah
Hey real quick what is going on with my raycast? it is not going out or anything i tried debugging it and everything it just does not want to go out
RaycastHit hit;
if(Physics.Raycast(rayStart, Vector3.down, out hit, Mathf.Infinity, whatIsGround)){
Debug.DrawRay(rayStart, Vector3.down, Color.black, 1000);
Debug.Log("Ray Start: " + rayStart);
Debug.Log("Hit Point: " + hit.point);
Debug.Log("Normal: " + hit.normal);
if(hit.point.y >= minHeight){
GameObject tree = Instantiate(prefab, hit.point, transform.rotation);
tree.transform.SetParent(prefabParent);
tree.transform.Rotate(Vector3.up, Random.Range(0, 360), Space.Self);
tree.transform.rotation = Quaternion.Lerp(transform.rotation, transform.rotation*Quaternion.FromToRotation(tree.transform.up, hit.normal), rotateTowardsNormal);
tree.transform.localScale = new Vector3(
Random.Range(minScale.x, maxScale.x),
Random.Range(minScale.y, maxScale.y),
Random.Range(minScale.z, minScale.z)
);
prefabArray.Add(tree);
}
}
wdym it's "not going out"?
Like when i start the raycast will not even raycast it hits nothing and their is no Drawray debug i have Gizmos on
it needs a normal distribution centered around 50%
@tiny orbit if you can solve this problem you can go way further than "10,000" dice
Well that means it's not hitting anything. Why don't you do a DrawRay OUTSIDE the if (or in an else) so you can see the ray when it doesn't hit anything
and if that doesn't do anything you need to make sure the code is even running in the first place
which means Debug.Log but OUTSIDE the if statement
Yea its running i have iteration for the for loop debugs and when it starts and ends ill try it outside the if statement
maybe. the following function is not wrong:
int NumberOfHeads(int coins) {
var heads = 0;
for (var i = 0; i < coins; i++) {
if (Random.value < 0.5f) {
heads++;
}
}
return heads;
}
what would be the right "choice" for variance of a normal there?
will not let me upload the fill script its to long i found the issue though it does not hit the ground witch means the Mathf.infinity is not going all the way down i beleave
!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.
you're close. just a few more steps on this journey and you'll find the right distribution
more likely the ray is simply in the wrong place, or the ground is simply not on a layer contained in the layermask
infinity is infinity
infinity not being long enough is definitely not the issue
I barely got a C in statistics 😅
the snippet i shared that is O(coins) is meant to illustrate that you couldn't possibly need a variance like Normal(mean, variance) does, because Random.value is uniform
well you better start getting an A in statistics, because you're making statistics games now lol
the ground has the layer mask the picture has how long the raycast is so its probably in the ground place?
what am I looking at here
The raycast line
and how is that being drawn?
and what layer is the "ground" on?
And how is the layermask set up?
anyone mind helping me out with this?
https://paste.ofcode.org/TRYie4QBss25VeCZBKsUKC
The layer mask is on layer 12
show the inspector of the "ground" object that you expect to hit?
Looks like it's deactivated
it's also... super far in the distance. 7k?
Everything will start getting fuzzy out there
I have it is a system where the farther away it is from the player its disabled but the closer it is its enabled
well it's not going to get hit by raycasts when it's deactivated
heres one thats closer to the player
where's the mesh coming from
custom meshes, especially non-convex ones, can have messed up geometry
which could cause physics queries to fail
That would be the render Queue correct?
What does this have to do with your mesh/mesh collider?
this is a material
it's for rendering
you're about to code* blue
it would be coming from this script https://paste.ofcode.org/gnDqpBWnANQE8kRMYr4GMr at line 111 is where it sets the mesh collider and all that for the mesh is what i believe your asking my bad
that's setting a material on your renderer
I'm not talking about rendering
I'm basically talking about where you assign a mesh to the MeshCollider
which seems pretty sketchy - you're doing it in some callback, you need to debug if/when that runs and make sure that's actually happening
and of course - the mesh itself needs to not be messed up geometrically
If I call scenemanager.load("Scene1"), then same for mainmenu, then load Scene1 again...why does Scene1 not "reload" and instead keeps continuing from last load? (Only happens on mobile)
Honestly i dont know much what that does i was just trying to get terrain generation so i started watching Sabastion leagues videos on it but it could probably be the way with the lod around line 194? i think the mesh its self is fine but i dont know
(When a new scene is loaded my players position resets...it doesnt reset between main menu and scene1 rn)
Cant find amything online...I imagine if I unload Scene1 it may fix it...but is that bad practice?
Is there a documentation about the background threads in Unity?
Ok finally got around to this, but isnt it just randomNormal * standardDeviation + expected value?
well in the O(coins) example you can see that there's no standard deviation
Hello everyone! I'm currently working on a weapon for my game which shoots mines similar to minesweeper. When the player shoots a mine, it should stick to the ground/wall it lands on and align itself along a grid. I've gotten the alignment working, however on certain surfaces things seem to break (angles and probuilder walls) Thoughts on what I could do to fix this?
private void CreateGridSpace(Collision collision)
{
Vector3 pos = transform.position;
int gridX = Mathf.RoundToInt(pos.x);
int gridY = Mathf.RoundToInt(pos.y);
int gridZ = Mathf.RoundToInt(pos.z);
Vector3 result = new Vector3(gridX, gridY, gridZ);
GameObject newGridObject = Instantiate(_gridObject, result, Quaternion.identity);
newGridObject.transform.rotation = Quaternion.FromToRotation(newGridObject.transform.up, collision.contacts[0].normal) * newGridObject.transform.rotation;
}```
(as you can see, sometimes the spawned tile just floats or becomes burrowed into the ground, some elevated higher than others on the ground)
0.5 * sqrt(coins)? or sqrt(.25/coins)
Hello guys, I am creating a script for ending the game when going through a box 2d collider(trigger) but in the condition that the boss is first defeated. Any ideas?
have some script which detects when a boss is defeated (health <= 0, or something along those lines) and store it as a boolean variable (isBossDefeated? true or false statement) then if the player tries to collide prematurely, the script will ask "has the player beaten the boss?" (you can use that bool variable to check this).
if false : you havent beaten the boss yet
if true : you win!!
I recommend having a game manager class of some sort to control important parts of your game rather than random classes.
Still not sure how this will help me though, because the probabilities for each die can be different
In probability theory and statistics, the binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent experiments, each asking a yes–no question, and each with its own Boolean-valued outcome: success (with probability p) or failure (with probability
...
sampling from the binomial distribution gives you the exact answer "given a coin weighted p=0.5, how many heads to i see if i flip 1,000 times"
this is the answer to O(1)
ok yeah makes sense
you can then continue this journey to see how this generalizes to dice
are you sure you don't have multiple player objects in the scene?
so in order to massively improve the efficiency of your game, you can sample these distributions to get the direct counts
you will have to express the player's collection of dice in a way that's useful for optimizing down the number of computations you have to do
so that you can do a mix of ordered and unordered computations, and simplify
fortunately, that is literally Algebra
for example, if the user had the following collection (i don't know anything about your game)
dice 0...16 are 6 sided, evenly weighted
coin 17 says, "0.75 weight, heads means double the previous score, tails means 0"
dice 18...29 are 6 sided, evenly weighted
you can seemingly do this in 3 steps instead of 30. but your game needs to be able to express the state of the user's collection in e.g. an algebraic way / appropriate format in order to be "simplified" into those 3 steps
does anyone mind helping me out with this?
in this case, it would be
sum(multinomial(17,6)) * {0.75 ? 2 : 0} + sum(multinomial(11,6))
@tiny orbit does that make sense?
yeah, makes sense, i could definitely cut down on the random calls for unweighted dice, I.m not really sure how much I cna extrapolate that to the rest of the game though
there is already algebra that can do
multinomial(x,6) + multinomial(y,6) = multinomial(x+y,6)
well it could apply to weighted dice
it doesn't really matter
i am advocating for a framework of optimization
i brought 30 steps down to 3, which is a 10x speedup
you probably expected a 20% speedup, and i'm giving you a 10,000% speedup
do you see what i mean?
anyway just think about it
it's your game
i think it's a cool premise for a little game
i liked dicey dungeons, i like dice, i like this
it's intriguing to move dice around in this huge order
it's intriguing if this works for millions of dice
yeah, I hear you
kindly send me a link to the pre-existing build 🙂 feel free to ping me and pick my brain
I need some AI coding help
I'm trying to get my enemy AI to jump if it detects a gap along the waypoint path
I came up with a solution but it seems to only work when the player is close to the enemy
There are 100's of different die faces though so i dont entirely know how to go about resolving their effects without checking each one
doing the algebraic simplification would be O(dice), but only once. there's of course no free lunch. simplifying the marginal dice would be O(1). you would need to run O(dice) whenever order changes, if that's something you can do in your game
i think we're going into the weeds of the specific things you're doing in your game and yeah, if you send me a build it would make more sense to me
i don't know if there's a more efficient approach than what i'm suggesting. it might be the general limit on how optimal this can get. i don't know how to "cache" random results, by definition those will be different each scoring
it may be that your game lets you do something of the form
random values * constant cached values
but i feel like the algebraic simplification will cover that. that is my gut
as long as the effects can be expressed algebraically, which seems like a valuable constraint imo for optimization, a general simplifier will help you
I can send you a build
you can send me a testflight link to the appleid i sent you, or if it's not necessarily super sensitive, you can always add me to github and boot me later lol
i'm happy to share a game with you as collateral. i don't think this stuff is very sensitive
100% sure
Have a prefab thats instantiated once when it starts, not even ina scene
Just in game resources
Bump
is there a way i can get my current scenes build index and assign it to an Int in my script?
Hey, my game is calling OnTriggerEnter twice for all objects in my scene, can anyone help explain why?
whatever object is triggering with them has two colliders
Thats odd, becuase it only started happening today with no change to my game that wouldve caused it...
maybe you just didn't notice, or forgot about a change you made ¯_(ツ)_/¯
check your colliders
#archived-code-general message
If you truly care about mobile optimization, I highly implore you to use DOTS for this kind of stuff. You will never, in a million of years, be able to compete against DOTS's pure and raw performance power it can offer. (Plus, it improves your mobile battery lifespan due to sufficient usage of memory calls!)
#archived-code-general message
Sounds like you are relying on guarantee answer from your 10,000 rolls, or has already been calculated ahead of time before the animation plays? You either trick the dice to roll into the "expected" side by compute ahead of time and play the animation, or simulate into the correct alignment.
Otherwise, what's the point of expecting the rolls be 50% all of the time? Use Random.Range(0,6);, Always use pseudo random generated number to avoid people predicting your game behavior.
Back to your original question, which all of this should've been in a thread a long time ago... Read the first paragraph! Took me forever ago to read through all of this!
A. DOTS computes the whole entity at once. It doesn't have to iterate 10,000 monobehaviour objects.
B. See DOTS! Check it out.
C. What do you mean "They are the same"??? Can you please elaborate more on this, for clarity.
Please watch this! https://www.youtube.com/watch?v=yTGhg905SCs
Far North Entertainment is working on a third-person zombie horde shooter using the Data-Oriented Technology Stack (DOTS), which has brought great performance improvements and influenced the development team's mindset to be more data-oriented in general. This beginner to intermediate level talk explains why DOTS is able to process data much fast...
I will, I'm sure it isnt a performance issue at least
anyone know?
Check out SceneManager API.
don't crosspost
oki
Is it possible to check if a an object is colliding with another object without OnCollisionEnter?
I am instantiating objects in random positions, and some are being placed inside other objects
use direct physics queries before spawning the new objects
Can you please elaborate?
which part are you confused about
"direct physics queries"
Stuff like Physics.OverlapBox etc
You should peruse the available functions here https://docs.unity3d.com/ScriptReference/Physics.html
Hmm, this could work thanks!
Although, what if I don't know the scale of the object?
the scale of what object
How are you spawning the object then?
I would consider making a scriptable object, which holds information that you can later modify and create collections, which expose size and shape of the object you're about to spawn.
It's super neat, and can be addressable 😄
Then whatever script you're spawning, would hold those scriptable class type. Implement a method inside your scriptable object script that can return you the size and shape you need to perform physics api in your scene. Having a container with necessary information helps solve complex problems.
What's the type for a field that accepts a VisualEffect graph object? Because public VisualEffect vfx doesn't let me add the vfxgraph
VisualEffect is the component that plays a VFX graph
which is usually what you actually want
But first, what are you trying to accomplish?
Sounds like an X/Y problem...
I want a gameobject to have a reference to a graph so it can play it whenever it needs to
Don't ypou want a reference to the VisualEffect component
so you can call Play() on it
See's @leaden ice response. Reference the component, and invoke it's implementation.
it's the analog to ParticleSystem
I don't know the unity scale of my object though lol
What component? I can't drag the graph into the field.
Typically you attach a VisualEffect to a GameObject, assign the graph to it, and play it with Play()
VisualEffect
Go to a GameObject
Add Component
VisualEffect
then drag your graph into the slot in that component
That's where you fill in the missing information! In the scriptable object, you can add fields along with the object you are going to spawn. Figure out how big your object, and record it down! Either that, or simply reference the collider that contains the information about size.
So I need to make a gameobject for each graph I want to be able to use?
Alright
Well no you can have one VisualEffect and replace the graph in it if you want
but if you want to play VFX graphs you need a VisualEffect component
I will be playing different visual effects simultaneously, so it sounds like I need to make child gameobjects with players, then reference those players in the parent gameobject. Right?
think of VisualEffect like AudioSource
VisualEffectAsset is like AudioClip
yes for each graph you want to "play" simultaneously you will need a VisualEffect component to play it
void StartGame()
{
SceneManager.LoadSceneAsync("Scene1");
SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene());
}
How should I be doing this?
Thank you for the idea. I sort used what you said and instead of a bool I used a null, since I destroy my boss's game object when it gets defeated.
has like a little glitch/lag when doing it this way vs just doing LoadScene
what are you trying to do
in short I am on my main game, scene1, I then click to go to mainmenu, I think try to go back to scene1 and scene1 hasn't "reset" and is just continuing from before I loaded mainmenu
so Im thinking I need to unload previous scene when loading a new one
I don't understand what you want to do though
oh with the code
you want to load the menu scene, asynchronously? Then unload the first scene once the menu scene is done loading?
Or what
after Scene1 is loaded I want to unload the "current scene"...current scene being Mainmenu in this instance
reposting as I did typos
You're using async methods
you need to start acting like it 😉
you have to either wait for the operation to finish
or subscribe to the asyncoperation's onComplete event
before doing the next thing
gotcha
any ideas why this doesn't seem to be "reseting" Scene1 to its "default" when something like this happens pretty quick?
since if I do stuff like this, it doesn't seen to unload the Scene1
SceneManager.LoadScene("Scene1");
SceneManager.LoadScene("MainMenu");
SceneManager.LoadScene("Scene1");
This is just... craziness
I don't know what you're doing here
LoadScene should never be called consecutively like this, especially if it's not async
well thats just essentially what it is
LoadScene takes a whole frame to complete
basically Scene1 has a pause menu, I click menu then it loads MainMenu
Is your code exactly like this
then in Mainmenu I click play which goes back to scene1
or did you do this for illustration
illustration
ok then I don't understand the question
The scene will always load in its "default" state
🤔
the only thing that will change that is any external data or objects your code is dealing with
like DDOL objects
or PlayerPrefs
or any data stored in any non-scene place that your code is accessing
SceneManager.sceneLoaded += LoadState;
....
public void LoadState(Scene s, LoadSceneMode mode)
{
if (!PlayerPrefs.HasKey("SaveState"))
{
return;
}
string[] data = PlayerPrefs.GetString("SaveState").Split('|');
// 0|10|15|2
// Change player skin
gold = int.Parse(data[1]);
experience = int.Parse(data[2]);
playerLevel = int.Parse(data[3]);
// Change Weapon Level
player.transform.position = new Vector3(0,0,0);
Debug.Log("LoadState");
}
main issue is just my player isn't being reset to 0,0,0 when new scene is called
which is confusing me
the problem is that it works inside my Unity
it breaks when I build and do it on my phone
player.transform.position = new Vector3(0,0,0); < note this won't work if your player object has a CharacterController or something
this is usually due to script execution order issues
you have some other script that is repositioning your player
and on the PC it's running before this
on the phone, after
Would avoid using PlayerPrefs! Serialize your object and save it to .json or other data struct files.
good to know thanks
100% agree...very old code that I haven't gotten rid of yet
thanks though 🙂
SceneManager.LoadScene("Scene1");
GameManager.instance.player.transform.position = new Vector3(0, 0, 0);```
after loadScene I added this and now it seems to work
not sure how doing the += here didn't fix it at all...seemed like setting the position did nothing on mobile
Build a interface that can be treated as interchangable pipeline.
I have no idea what that means 😄
You can create a persistence connection handler. Treat it as a way to make your script choose which strategy to use to save your game data.
You can then create a class that handles parsing data from player pref, and slap that [Obsolete] tag on that.
Then in the future, you can create another connection to handle, say dropbox!
at the ease of changing the script reference.
(Code in GameManager.instance)
SceneManager.sceneLoaded += LoadState;
public void LoadState(Scene s, LoadSceneMode mode){
player.transform.position = new Vector3(0, 0, 0);
}```
that doesn't successfully set the players position to 0 when loading scene
but this does...wtf?
SceneManager.LoadScene("Scene1");
GameManager.instance.player.transform.position = new Vector3(0, 0, 0);```
Does this use playmaker or something?
I have a dodge system in my 1st person game where pressing a key will dodge to the left and tilt the camera, however for some reason during the tilt if i move my mouse to adjust the camera during the tilt nothing happens, and it wont update until the tilt finishes. This happens with 2 different methods,
StartCoroutine(CameraTilt(dodgeDuration, Quaternion.Euler(0,0,19f)));
IEnumerator CameraTilt(float duration, Quaternion tilt)
{
float tiltTime = 0f;
Quaternion startTilt = playerCamera.transform.rotation;
Quaternion endTilt = startTilt * tilt;
Quaternion newRot = playerCamera.transform.rotation;
Quaternion oldRot = playerCamera.transform.rotation;
while (tiltTime < duration)
if (tiltTime <= duration/2)
{
playerCamera.transform.rotation = Quaternion.Slerp(startTilt, endTilt,Mathf.SmoothStep(0.0f,1.0f,tiltTime/duration));
tiltTime += Time.deltaTime;
yield return null;
}
else
{
playerCamera.transform.rotation = Quaternion.Slerp(endTilt, startTilt,Mathf.SmoothStep(0.0f,1.0f,tiltTime/duration));
tiltTime += Time.deltaTime;
yield return null;
}
}```
as well as when just using a simple tween
```playerCamera.transform.DORotate(new Vector3(0,0,10), dodgeDuration/2, RotateMode.LocalAxisAdd).SetLoops(2, LoopType.Yoyo).SetEase(Ease.InOutSine);```
any ideas what might be causing this?
because in your coroutine you're setting the rotation
so any other code that changes the rotation will be overwritten by that
playerCamera.transform.rotation = < forget this is a rotation for a second. Imagine this was just saying x = 5;. You're doing that each frame. Even if you wrote x = 7; in some other code, the x = 5; is just running every frame and will overwrite it
nah
nothing wrong with the coroutine
What I would do here is add an empty parent to the camer
the normal mouse look code would rotate the parent
the tilt coroutine would tilt the child
then it'll all work together
atm I have all my movement in FixedUpdate because I use rigidbody stuff...however I think using FixedUpdate is causing a lot of movement blur when lowfps on my mobile game, what could I do to keep things like colliders, but not use fixedupdate?
You should use FixedUpdate for physics-based movement
Just make sure you turn interpolation on for your Rigidbodies
I already have that
I have major blur when my character is moving and the background isn't moving rn
then that would not be the cause of any "movement blur"
I've tried most every other fix I've found outside of "move everything out of fixedupdate"
how could I possible fix the "blur"?
I've tried getting rid of cinemachine, no fix
just moving my character in pretty much an empty scene causes blur on mobile
I get lowfps maybe
could it be that all my animations have 60 sample rate and mobile devices have 30fps?
I've basically tried almost any fix I've found on the internet 😭
I'm not even really sure what you mean by "blur"?
It could just be a display artifact
if you see, when background is moving the character appears to be a lot cleaner
nah
just when the character is not stationary in screen space
nothing to do with the bg
to be clear I don't actually see any blurring here
huh, good to know thanks
yeah its harder to see in the gif
its super bad on mobile
Do you have motion blur in post processing on?
what could I do to try and fix this?
its borderline unplayable atm from the major blur when character isn't stationary in screenspace
sorry just to clarify, do you mean adding the empty object to the camera then tilting that, or do you mean using that empty object for the mouse movement rotation instead? as if it’s the latter, that already is the case as the camera is already a child of an object which is being rotated by the mouse movement
thinking moving animations down from 60 sample rate->30 might help? (at this point I have no clue what might help)
@thick socket ?
where would a setting like that be at?
couldn't find it earlier
I've got Anti Aliasing disabled
I'm having bit of trouble trying to figure out how to change the import settings of a texture to Sprite(2D and UI) through code, but I'm getting a null reference exception on the line "importer.isReadable = true" which I assume means I'm not actually getting the TextureImporter. Any chance someone knows how to do this?
Here is my relevant code:
importer.isReadable = true;
importer.textureType = TextureImporterType.Sprite;```
Link to full script: https://gdl.space/amutahumak.cs
Check maincamera, does it have "post processing" ticked on?
I've never seen a post processing thing
Wait is the project an HDRP?
¯_(ツ)_/¯
yes the latter:
- mouse movement rotates the empty parent
- coroutine tilts the camera itself in local space (right now you're controlling the camera rotation in world space in the coroutine)
I'll let praetor handle this one then, no clue 
when I started it initially I clicked 2D project and start 😄
Might as well try after enabling that
@leaden ice any ideas for fixing blur when character isn't stationary in screenspace?
I have no idea what is causing your blur so no
(also I could send you the apk if you wanted to see how terrible the blur was...its bad in bluestacks also)
dam
in general what would cause blur when not stationary in screenspace?
maybe you need to be using the pixel perfect camera?
I'll look into it
what is with imgur and uploading every video as like 144p lol
recorded bluestacks
the blur is pretty apparent when you can watch 1080p lol
but the mouse move already does rotate a parent of the camera rather than the actual camera itself
@hasty canopy figure I ping you with a link to it just so you can see since you helped some also 🙂
Looks fine ngl
did you watch it on like 1440p?
I watched at 720p
it looks completely fine to me too...
1440p, starting on the left and moving right shows how bad it is
u sure its not a screen issue or something
happens in bluestacks and on mobile
Watched on 2k and dammit praetor you beat me to it lmao
@thick socket also in platformer games people don't really look at player much, it's the surroundings that are the main focus so don't worry about it
its at the 3-5s mark thats really bad imo
thats fair
but its super obvious to me which will drive me nuts 😄
¯_(ツ)_/¯
I can see it clearly on 2 very different monitors and 1 phone
its really not blurry for yall at that 3-5s stretch?
even if you are looking for it?
cinemachine fixedUpdate makes it better...however then the camera is jittery 😭
I just can't win lmao
Instead of using FixedUpdate, use LateUpdate() to make final camera transformation.
also, definitely start using transform.SetPositionAndRotation(); methods if you plan on modifying both position and rotation at the same frame.
I always forget about this!
You can access transform anywhere, how are you able to do that, something to do with MonoBehaviour?
Component actually
MonoBehaviour implements transform property.
want to shoot a raycast from the mouse but the position of the raycast seem to only be 0,0,0
why not just use the ray you already created
@leaden ice @plucky karma Since MonoBehaviour implements it and it’s a part of Component, that’s why there’s no need to do GetComponent to access it? I know a long time ago .transform used to do GetComponent behind the scenes
You still need GetComponent if you need reference to other component beside the current component you're writing in.
MonoBehaviour is a subclass of Component, yes, so it gets all of Component's properties and methods
can't get the position from the ray I think?
I wonder if it's ideal to simplify the code for quaternion into two degrees angle for multiplayer solution?
that is why I am using a raycast?
E.g. if I'm doing a first person shooter, I know the character doesn't needs all three degree of rotation.
sure you can
but you don't need to
how?
ray.origin though
what about hit.point?
So like the players body doesn’t need to look up or down?
might try
That's one degree of rotation, You can go left or right.
also your transform.rotation = line is very wrong
Never could I find a reason why I need to rotate my character like a cartwheel
how?
transform.rotation.y is NOT an euler angle
you can't use it like one
Lmfao yeah as long as it’s more performant gotta restrict as many things as possible for multiplayer
Is it just me or navmeshagent autobraking seems to do nothing?
Like allegedly you disable it and the agent won't suddenly stop, but nope, it suddenly stops when it reaches destination.
Max speed to 0 instantly
it's supposed to be this: https://www.youtube.com/watch?v=Kro0JwyZlsM&t=2m
but in reality it's this:
https://www.youtube.com/watch?v=Kro0JwyZlsM&t=1m20s
regardless of settings
Short video explaining what the new NavMeshAgent.autoBreaking function does in Unity.
Short video explaining what the new NavMeshAgent.autoBreaking function does in Unity.
Stopping distance does everything, autobraking does nothing it seems
I need some help regarding the implementation of ScriptableObjects.
I have a ScriptableObject called Item. I can create these in the editor.
But let's say that I want to have different types of Items which have different functions.
Should I create more ScriptableObjects which inherit the class Item, i.e.
Base: Item : ScriptableObject
New Type: Weapon : Item
New Type 2: Book : Item
Obviously, a book and a weapon are going to function completely differently, but are both a type of object that would be held within an inventory.
The alternative in my mind is having a public enum ItemType in my Item class. So each Item could be selected in the inspector as a Weapon or a Book, and execute different code according to that enum.
What is the standard way of going about this?
How do I invoke with delay in a scriptable object?
I would not go as far as calling anything in gamedev standard but inheriting is a very good approach. If I was doing it I would do it like that.
I've just implemented the same thing.
I have the base class named Item, inheriting from SO.
Then Equipment inherits from item, consumable inherits from item... and so on
And then equipment is broken down further into something like weapons and armor, which both inherit from Equipment
I wouldn’t do that at all. Scriptable objects should just hold data it makes life so much simpler. The fact that methods are even allowed in SO is bad imho
Tell it to Unity which put many methods into SOs
Working on tiles and having a bunch of methods here
And each tile is an SO
I have told them many times. It all began with a unite lecture years ago that was” and guys you can totally even have methods inside the SO’s isnt that cool” next thing you know people are making entire architectures around this.
What if your player was doing a cartwheel
At best methods in an so should be connected to the data like return random between min and max values where min and max are defined in the so. Doing any gameplay logic inside a so is major code stink and leads to big problems
Class B inherits from abstract class A
I want a field or property on class A called "MyName". I want this field or property to be required to be defined and given a value in class B.
How do I set this up?
The enum thing is pretty standard in editors yeah. You could do smth like:
enum ItemType { Base, Weapon, Book, ... }
Dictionary<ItemType, Type> EnumTypeToCSharpTypeMap = new() {
{ ItemType.Base, typeof(Item) },
{ ItemType.Weapon, typeof(WeaponItem) },
{ ItemType.Book, typeof(BookItem) },
...
};
//Editor
Item CreateItem(ItemType itemType) => (Item) ScriptableObject.Create(EnumTypeToCSharpTypeMap[itemType]);
I assume your editor already handles the inspectors of different types, and you're just looking to create the different types
hi
abstract class Parent
{
protected float myFancyFloat = 0;
abstract public int MyInt { get; }
}
class Father : Parent
{
public override int MyInt
{
get { myFancyFloat = 1; /* Apply formula "X" and return a value */ }
}
}
class Mother : Parent
{
public override int MyInt
{
get { myFancyFloat = 2; /* Apply formula "Y" and return a value */ }
}
}
Something like that? (From google)
You cant do this. You can have abstract/virtual properties but not fields. If B needs a concrete implementation of the field just define it in B
@main shuttle Thank you soldier, that is very close to what I am after
I am wanting to give MyInt a value in Father/Mother
So just give it ?
i might be retarded but, how?
abstract class Parent { public abstract string Gender { get; } }
class Father : Parent { public override string Gender => "Male"; }
class Mother : Parent { public override string Gender => "Female"; }
scriptable objectiles
you could just expose it to the inspector
Oh yes excellent thanks everyone for the code examples, that makes sense now!
What pumpkin said or you can set it in the Awake of B
Abstract is the way to go with this, which is what @stable osprey perfectly described @vague tundra
Hey everyone, is it possible to extend the Debug.Log to get the calling method without actively passing it to the extension?
hi everyone, I would like to ask how can I get vector b if blue point is moving around the centre (enemy) as a circle?
I have tried the following code in Update but it doesnt work.
float angle = 60;
Vector3 angularDirection = (transform.position - enemy.transform.position) / Mathf.Cos(angle*Mathf.Deg2Rad);
angle = angle + Time.deltaTime * 60;
Unlikely to get the method itself without some VERY heavy reflection..
There's System.Environment.StackTrace and UnityEngine.StackTraceUtility.ExtractStackTrace which you can use to get the Call Stack as a string -- but you'll only get the related stack trace out of it
Also, even if you DO get it, depends on -- get it and do what with it?
You can create your custom Logger/LogHandler and even write the messages in a custom way with ILogWriter, so if you just wanna print the calling method it should be fine, but navigating to its definition will be even harder than getting it 😛
Yeah I just extended the Debug.Log to output colors, its just for better visual order in the console/logs. I also used application on message received in other projects for runtime, was jsut hoping there was an easy way without just passing in the object as object param. Well, but I am fine with that then I guess 🙂 thanks 🙂
r u in 3d or 2d space?
you can take float angle = 60; out of update and have it as a class member
then do: enemy.transform.position = player.transform.position + new Vector3(Mathf.Cos(angle * Mathf.Deg2Rad), 0, Mathf.Sin(angle * Mathf.Deg2Rad)); in Update -- before adding to angle
'getting' the position uh.... isn't that just enemy.transform.position?
oh you're looking to get the direction, I see -- so the tangent of the circle on point B
2d
Yea i know the enemy position but i want to get the red vector b
Oh nice, so B will be the line perpendicular to AB, at some distance along the line in the direction of B
one option is to calculate the position on angle = angle + 1, then normalize the difference between current point and next point 😛
pretty sure there's a math way, but cba rn 😄
First step is to get the vector AB, which is your enemyPos - playerPos
Then find the line perpendicular to to AB, which will be Vector2.Perpendicular(AB)
Oh i forget the angle is always 90 if it is the radius
Nice
I feel like my explanation is incomplete but sounds like you'll be able to figure it out now
How do I check if an objects name contains the string "Tank". I may or may not have many clones with name Tank but I can use this.gameObject for it
tankObject.name.Contains("Tank"); @fiery warren
Thank you
Just an idea, but if you did want the object, you could maybe make a extension function, like for example
public static string Log(this Transform me, string context) { Debug.Log(context, me); }
Then you should be able to do something like someObj.transform.Log("hi"); if your interested in getting the object, though that wouldnt give you any stacktrace info on its own, you could do what you need with he object from the static function, as a possible extended option - and you dont really need to pass "me" to the log line, if you dont need the object pinged from the console, but im assuming this is more for use in a build than the editor itself
The problem here is, I still pass in the object, even if its just in case of calling transform first and then Log. And that would make me extend every class manually, which is even worse to handle, but thanks for the idea! 🙂 This would just move the passing to .transform. isntead of me in the log tho
Ah, I figured if your trying to call from the object, youd probably be on a transform or game object or mono class already where the log is called from, but if this is meant to be used outside of a object just as a global class, then this probably wouldnt work
Right now I am using this. As this is only for dev outputs , I will not put too much effort in here to make it prettier 😉
public static class Debug
{
public enum LogType { Data, System, User };
public static void Log(object msg) => UnityEngine.Debug.Log($"{msg}");
public static void LogError(object msg) => UnityEngine.Debug.LogError(msg);
public static void LogWarning(object msg) => UnityEngine.Debug.LogWarning(msg);
public static void LogException(System.Exception msg) => UnityEngine.Debug.LogException(msg);
public static void Log(object msg, object caller, LogType logType = LogType.System)
{
string callerName = caller != null ? caller.GetType().ToString() : "Global";
switch (logType)
{
case LogType.Data:
UnityEngine.Debug.Log($"<color=#FFFFFF>{callerName}: {msg}</color>");
break;
case LogType.System:
UnityEngine.Debug.Log($"<color=#FFFF00>{callerName}: {msg}</color>");
break;
case LogType.User:
UnityEngine.Debug.Log($"<color=#FFFF00>{callerName}: {msg}</color>");
break;
}
}
}
How do you collapse stuff again, well, might be fine 😄
Ah I see, well, if it works (and is largely for dev builds to make tracking runtime problems easier) then it seems like a good approach to me :p I would imagine youd be manually calling Debug.LogError or whatever in specific parts of your code anyway
I had to introduce it in the extension, otherwise I would have to call ot UnityEngine.Debug everytime I want to use the built in function
Can I set a const in Awake?
Ah yeah that makes sense, thats probably as convenient as you could get it in Unity, since youd have to pass the object somewhere at some point
A const value is set when its declared, I dont think you can set it at any other point in a function, it wouldnt really be "constant" if you could - what are you trying to do?
Just want to grab the value of a UI elements rectTransform on startup and save that in a const
I found my game is stopped intermittently and quite frequently. So I did profiling about it and I got this result. It looks Text (Legacy) or Text Mesh Pro occurs lag but, I can't imagine and guess what is actually happening and what is wrong. May I get some insight?
Why not use a property instead?
Yeah could do I guess, currently just using a field and its perfectly fine
Only reason I want it to be a const is cause I want it to kinda be a const, just one that can be declared on startup, and am wondering if thats possible out of curiosity
Can a property be setup such that it can only be given a value once and then it becomes readonly or something?
Not a lot of info in your story, but if you have a canvas with hundreds of UI elements, dirty'ing 1 element will cause a redraw of everything in that canvas. You could get huge lag spikes like this then.
Then can I avoid it by adding canvases as layers?
Yeah, that's 1 step. There is a blog about it from Unity. The last guy I helped with it, needed to also stagger the updates of the UI, because even with different layers it would still lag updating hundreds of UI elements.
Really appreciate it!
You could make a private variable you set once, then have your public property return that so its only a get, otherwise, unless the object already exists, you might be able to set it with = with just a get property, or make the set private, otherwise I dont think you could easily set the property in Awake/Start, AFAIK
Cool cool, sounds good. Thanks!(:
for some reason this isn't working, i have looked online and tried troubleshooting can't find a solution (it's a music slider btw). In the editor it works but in the build it doesn't work, there aren't any error messages
using UnityEngine.UI;
using UnityEngine;
public class SoundSettings : MonoBehaviour
{
[SerializeField] Slider soundSlider;
[SerializeField] AudioMixer masterMixer;
private void Start()
{
SetVolume(PlayerPrefs.GetFloat("SavedMasterVolume", 100));
}
public void SetVolume(float _value)
{
if(_value < 1)
{
_value = .001f;
}
RefreshSlider(_value);
PlayerPrefs.SetFloat("SavedMasterVolume", _value);
masterMixer.SetFloat("MasterVolume", Mathf.Log10(_value / 100) * 20f);
}
public void SetVolumeFromSlider()
{
SetVolume(soundSlider.value);
}
public void RefreshSlider(float _value)
{
soundSlider.value = _value;
}
}
it works no problem in the main menu scene but in the other scenes it doesn't work
Hi! Just curious, you know when you create a Serializable C# class and try to make an array of those classes, you have your elements that are called "Element i" with i the index. Example on the screenshot.
I know that if you put a string (whatever the name, i put "name" but could be anything), the name of the element changes!
Anyone know what i could do to modify this?
!cs
How are you using this component?
its a slider that changes the volume
Did you assign the serialized fields in the other scene?
yes
in the setting menu you can change the music volume, but it doesn't apply in other scenes
So you have a different menu in both scenes?
Why not apply Destroy on Load on the menu if you use it in multiple scenes?
Then you don't have the hassle of saving and loading being dependant on the scene
i've never used destroy on load before
Calling this on your menu canvas is going to move it to a seperate additive scene, which you can't delete. It will then persist between scenes
This way you always have the menu. You could add disable/enable methods to it to disable it at moment when you don't actually need it.
OverlapBox doesn't return any of that info. You'd want to use a cast like a BoxCast or Raycast. Or just get the closest point of the collider(s) detected
https://docs.unity3d.com/ScriptReference/Physics2D.ClosestPoint.html
it should be fairly obvious how to use that. you clearly have to loop through the array returned by OverlapBox then use Physics2D.ClosestPoint passing in the position you want to get the closest point for (typically the position your overlapbox would originate at) as well as the collider then it returns a Vector2 representing a point on the perimeter of the collider that is closest to the specified position
Hey, how can i highlight a quad of a plain using mouse?
I have an gameobject taht I am rotating every frame through code for a smoother effect. Is there a way to stop rotating it when it EXACTLY rotates 90 degrees? Currently its 90.1 or something similar.
once it reaches 90 degrees or higher just set it directly to 90
yeah but sadly with my current implementation some objects have rotations from before.. it might start from 90 and need to rotate to 180
what method are you using to handle the rotation?
if ((initRot < 90.0f))
{
if (!oppositeTurning)
{
if (timer > 1.5f)
{
initRot += onLeftRoad ? 21f * Time.deltaTime : 30f * Time.deltaTime;
transform.Rotate(onLeftRoad
? new Vector3(0f, 21f * Time.deltaTime, 0f)
: new Vector3(0f, 30f * Time.deltaTime, 0f));
}
}
else
{
if (timer > 4.5f)
{
initRot += !onLeftRoad ? 25f * Time.deltaTime : 35f * Time.deltaTime;
transform.Rotate(!onLeftRoad
? new Vector3(0f, -25f * Time.deltaTime, 0f)
: new Vector3(0f, -35f * Time.deltaTime, 0f));
}
}
}
this happens in update
transform.Rotate then 😛
- ClosestPoint returns a value so you have to assign it to something.
- have you never looped over an array before?
I'd go with a method like https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
MoveTowards, RotateTowards, and xxxxxxTowards in general are super useful when you have a target and want to avoid overshooting
Thank you sir! I will give it a go now
using transform.Rotate pretty much bypasses any clamping you might do. you'd want to track the rotation variable yourself and just assign the rotation so that you can clamp the angle before setting the rotation.
if you search "clamp camera" in this discord you'll find a bunch of different examples of how to do that (once you get past all the results of me suggesting people search that)
np, hope you're prepared for some eulerangle shenanigans 😛
Idk if this really belongs here, often in modern languages including c# fields and properties are combined, that being said Unity seems to punish this behavior. I’ve seen chatter on various websites that using fields directly is bad practice, so should I be creating a property for every field?
what.. why would u be doing that? 😄
Also Microsoft seems to reinforce this logic
-- in any languages
now you should still have compile errors because a transform is not a Vector3, but you're logic is backwards. also you should be passing the collider as the Collider parameter
I'm pretty sure making a property for every field is just a bad practice started by random youtubers making tutorials
you don't need a property for every field, just ones you want to be accessible outside of the class. using properties over public fields is preferred to maintain proper encapsulation of your data and to abstract the inners of the class away from outside sources
I’m not using YouTube as a reference here
if you get more specific on what your understanding of 'punishes this behaviour' is, I may be able to clear any misunderstandings up
your array that you are looping over is an array of colliders
remember how i said to use the origin of the overlapbox for the position and the colliders in the array for the colliders used as the method arguments?
By default declaring a property in C# will instantiate a related field, it’s built into the language, but inn Unity you need to declare fields to serialize them without just leaving them public
you can serialize the field of an auto property by targeting the backing field in the attribute [field: SerializeField]
or you can serialize your explicit backing fields if you aren't using an autoproperty
Oh interesting that would be far less time consuming
The second option has been my experience thus far
But it’s time consuming and a lot of code
public string myStr; //WILL show on the inspector
[SerializeField] string myStr; //WILL show on the inspector
string myStr; //WONT show on the inspector
public string myStr { get; set; } //WONT show on the inspector
[field: SerializeField] public string myStr { get; private set; } //WILL show on the inspector
[field: SerializeField] public string myStr { get; set; } //WILL show on the inspector
So I know what shows up in the inspector it’s more about creating a SOLID code base now
Pun intended
what I like as rule of thumb for the inspector is to only expose variables that do not change at all in runtime -- so anything u set via the inspector will remain there forever
and if I need a public member that DOES alter in runtime, I use a public auto-property
I’m less worried about the inspector, more about security
so I love that auto-properties don't get serialized
security in what sense? from human-error?
Is having exposed getter and private setters risky at all
access modifiers have nothing to do with the security of your application
well, if you think about it you're always in the 'risk' of a coworker simply deleting your script... lol
best you can do is minimize the access modifiers to the bare minimum while keeping the system functional

oh well right.. for max app security you want to hold all your data in a server, and only access it to render to the UI/game like so: public int Coins => MyServerAPI.RetrieveResult<int>("coins", userID); ..or something
anything less than that the player can alter it via some memory altering app or fake packets. but you really shouldn't care imo 🙂
Please just make sure that anything that has to be fetched from anywhere outside of your application (file, remote API, whatever) is done asynchronously
So technically not this as this will lock up your application until it is done
The reason I had to use late update iirc is because the players animations were changing head rotation and I wanted to look at enemy while fighting
So not sure I could use that method?
That's a good idea! Again, I really push the idea of having a game manager to manage these game events. Also an interesting thing to look into is delegates and events. Delegates and events are helpful because other classes can subscribe to them and call their own functions from those calls. You could have an event that is called from the boss (OnBossKilled()) which other classes subscribe to and perform their own logic without needing to know the boss at all. Another thing you could do (a bit more of a hacky method) involves just checking whether or not the boss is null. When you destroy the boss, it will become null since the reference to the boss no longer exists. (if(bossGameobject == null) // logic here)
i strongly recommend delegates and events tho for clean, abstract, and reusable code!
https://www.youtube.com/watch?v=G5R4C8BLEOc&ab_channel=SebastianLague
In this two-part series we'll be looking at delegates and events.
This episode covers how delegates can be used to pass methods as arguments into other methods. It also very briefly touches on lambda expressions.
The next episode can be found here:
https://www.youtube.com/watch?v=TdiN18PR4zk
If you'd like to translate this video, you can do so...
public static void AddAttachment(this Weapon weapon, string attachmentName)
{
bool AttachmentExists;
for (ushort i = 0; i < weapon.WepData.AttachmentsData.AllAttachments.Length; i++)
{
if (weapon.WepData.AttachmentsData.AllAttachments[i].Name == attachmentName)
{
AttachmentExists = true;
break;
}
AttachmentExists = false;
}
if (!AttachmentExists) return;
}
``` Use of unassigned local variable 'AttachmentExists'
would it be fine if I just initialize that bool value? It's gonna change anyways so
It should start out as false, there's no point in setting it to false every time in the loop
actually the entire thing is pointless, the function doesn't do anything
I'm trying to check if the attachment exists first
Allow me to improve your code with linq
public static void AddAttachment(this Weapon weapon, string attachmentName)
{
if (weapon.WepData.AttachmentsData.AllAttachments.Any(x => x.Name.Equals(attachmantName, StringComparison.OrdinalIgnoreCase)))
{
// Attachment exists
return;
}
// Don't forget to actually add the attachment here!
}
Also ensures case sensitivity is not an issue
Linq's Any method returns true if anything matches the predicate
x => x.Name.Equals(attachmantName, StringComparison.OrdinalIgnoreCase) is the predicate, and means that if any name in AllAttachments matches the attachment name, return true
Linq is a good thing to understand
eh, thank you
Beware of LINQ. It is a powerfull tool, but it is less performant than standard for loop. Also, I wouldnt recomand LINQ to people that start or have less experience in programming.
In my opinion, I feel that the data structure being use might be at fault here and usage of dictionary for AllAttachments would be better.
I would agree with you if this was a method that would invoke often, and I don't think that it's the case.
You know that, but the user that you are showing this might not know the difference.
Also, is there a reason why the function is an Extension ?
Even then, linq aint that bad as you're making it seem. There are more performant ways, but using linq is not gonna break your performance lol
The biggest problem comes from people using it wrong. I.e. with IEnumerable types
this method will run once but LINQ seems like these python functions, they look very simple but also generating garbage a lot according to what I've heard
Believe me, it is going to break your performance because of allocation.
Thank you regardless @thin aurora
Again, I would agree with you if the method ran often
But in comparison with regular methods, speed and allocation are only slightly worse
And there are plenty of benchmarks that proved it
Also, as of .NET 7, Linq is faster than manual enumeration I believe
Too bad Unity is so behind
Also, no allocation at all
Not, they are monstrously worse. Memory allocation is the slowest thing you can do. When you optimise, you remove ALL allocation that are not necessary.
It's literally benchmarked
.Net 4x
Yes, Unity is behind, I said that
But linq is open source
You can always copy it, and I would prefer that over reinventing the wheel
You cant... they would have use functionality from newer c# version.
But idc what you do. It's been used in every job I worked, even those still stuck in .NET Framework, and as long as you use it right there is no problem with it
That is true. If .NET Standard 2.1 does not support it, you can't do it.
Which goes directly toward I said earlier. People here might not be able to know here is right and where is wrong.
I use it myself. In Awake/Start/Event or editor tool.
I wont be there for that...
holy shit
Hi guys! I ran into a prob with my script, I followed a video tutorial about double jumping and did exactly like in the vid, the prob is that it didnt work for me unfortunately! Here is the script in the video.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float horizontal;
private float speed = 8f;
private float jumpingPower = 16f;
private bool isFacingRight = true;
private bool doubleJump;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private Animator animator;
private void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
if (IsGrounded() && !Input.GetButton("Jump"))
{
doubleJump = false;
}
if (Input.GetButtonDown("Jump"))
{
if (IsGrounded() || doubleJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
doubleJump = !doubleJump;
}
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
Flip();
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
Vector3 localScale = transform.localScale;
isFacingRight = !isFacingRight;
localScale.x *= -1f;
transform.localScale = localScale;
}
animator.SetFloat("Speed", Mathf.Abs(horizontal));
}
}
And here is my script
!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.
!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.
how do i round to the nearest 0? For example if I have 92 I want it to be 90 If its 87 I want it to be 90. if its -86 I want it to be -90. Is there a way?
you're probably looking to round to the nearest multiple of 10
yes that
google "how to round to nearest multiple of 10 c#"
is it possible, when deserializing JSON to a struct, to convert an array with 2 values into a class that has properties called x and y?
struct
public struct Position
{
int x;
int y;
public Position(int x, int y)
{
this.x = x;
this.y = y;
}
}```
json = `{ position: [5, 13] }`
Anything is possible. It's not possible with JSONUtility though
Still doesn't fix it, looks the same as using smart update 😦
Please format your !code properly using these sites 👇
📃 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.
important question ... how do i make a rigid body change the gravity (despite what the physics settings of the project might be)
how would i remove this certain tile from this array
I can only find "array.Remove(number)" on google
remove(i), then
but if you're removing while iterating, it needs to be a reverse loop
that doesnt work
show what you're doing now
I said. Remove(i)
and pay attention to what I said about looping in reverse
oh, that still gives this error
alright, i shall try that
what type is tile..
I recently noticed that animator is expensive, and people suggest that you can actually implement simple animation(eg. walking) without using animator. How should it be done? Any keywords that i can search?
Oh. Really?
Change Transform[] into List<Transform>
Be sure to initialize it with new List<Transform>
and you'll need Count, not Length
A list will change its size automatically when you add/remove items
I believe Length is still a valid method with Lists
But Count/Count() is recommended
I see.
Arrays are only useful if the size does not change. Otherwise you need to create a new array
Hi guys! I am trying to make a static class that allows me to receive the start callback from any class, even from Scriptable Objects (basically inside the static class I create a new gameobject with a custom script that saves in a list all the functions that want to be called on start and then on start I call all of them)
But Unity gives me this error: Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?) Why? (take in consideration that the SO could even call that function during edit time
You should not manually alter the way Unity lifecycles work. A ScriptableObject has its own lifecycle methods, and trying to hook others onto this might not work as it might be at a different point. Is there a reason why you do this?
Why would this be? Im trying to find game objects with the tag "tile" and put it into my array
tile = tileparent.FindGameObjectsWithTag("tile");
Yeah it's actually a NetworkStart and I need my ScriptableObjects to register for some network events (and to register for a network event I have to receive the NetworkStart callback first, so this is the only way I can think it would work)
It's probably better to make a singleton to whatever contains NetworkStart, assuming its a single instance, and then get NetworkStart
That said, I don't think SO's should contain much behaviour, should they? Maybe you should move this code to whatever consumes the SO
You're trying to set a Gameobject array into a Transform array
nah, its no longer a transform array, i changed it
I also managed to fix it
tile = tileparent.FindGameObjectsWithTag("tile").select(x => x.transform);
What was the issue?
It's more flexible with SO, since I need to have references to those scripts in multiple scenes and without SO I would have to use Singletons all over the place
I was trying to make "GameObject" "tileparent" to try and get it to only look for child gameobjects under the tileparent gameobject. I fixed it by just making it GameObject, and i guess it still works, just looks for every object
I was previoulsy just getting the child tiles, and was trying to remove specific tagged ones, not sure why i didnt think of this earlier
however this is no longer working.... It was working when it was transforms, but now they are gameobjects
unity editor question, how do you reset an instance's values without changing the name of the instance?
public AttachmentsData.Attachment LaserSight = new AttachmentsData.Attachment { Name = nameof(LaserSight).AddSpacesBetweenCapitals(), Type = AttachmentsData.AttachmentType.Laser };```
I know this might look like a useless question but it would save me tons of time afterwards
yeah..
tile[++currentIndex].gameObject.tag = "tile";
doesnt work
not sure why
Gonna need your whole script
And maybe explanation on what you're doing
you probably should not be using scriptable objects
you should describe your laser sight with a prefab
if you need to clear values, you can go ahead and write the initial values you need to the object. but it's not clear to me why you need to reset them
public class Tiles : MonoBehaviour
{
public GameObject tileparent;
public GameObject[] tile;
public int currentIndex = 2;
public AudioSource audios;
// Start is called before the first frame update
void Start()
{
tile = GameObject.FindGameObjectsWithTag("nexttile");
}
// Update is called once per frame
void Update()
{
}
public void OnTile()
{
if (currentIndex + 1 >= tile.Length) return;
tile[++currentIndex].gameObject.tag = "tile";
if(!audios.isPlaying)
{
audios.Play();
}
}
}
Basically its getting all of the tiles tagged with "nexttile" and when i call "OnTile" from my other scripts, it should add 1 to the current index, and tag the current index as tile (the next tile).. it also plays a sound
@thin aurora
maybe try #💻┃code-beginner
you shouldn't be using scriptable objects
you should simply create one monobehavior script and attach it to an object in your scene
and in its start method, write what you need to do to initialize the things you need
Can you move this to #💻┃code-beginner and send me a screenshot of the hierarchy of your tiles?
anyway, the editor has a reset button in the inspector, but it applies to the whole component.
yeah, the question was kinda unnecessary, thanks anyways
you could write a custom editor if it's very important to you, or modify the text of the asset directly in your IDE
specifically, you can create a [ContextMenu] that stores the name variable, calls Reset on the component, then restores the name
might be as few as 4 lines
that sounds interesting, will check it out thank you
Hey guys, I am unable to get any form of text (legacy or TMP) working on Unity 2022.2.x. These boxes show up. It works on any other Unity Editor version though. Anyone knows what's going on?
Tested on Unity 2022.2.5, 2022.2.1, 2020.3.29, 2022.1.3
only fails on 2022.2 :/
We haven't had a 2022.x pass our internal QA (yet). But if it does that with clean / new projects it may be good to submit a bug
Okay, it seems to be a project bug. Reimport all didn't fix it, but a git clean -fdX did. Found out when I converted a 2020 project to 2022 and it suddenly works. Mind you, a fresh project of 2022 didn't work.
How can I make a navmeshagents decelerate gradually instead of stopping instantly at its destination? Autobrake is supposed to affect this but it doesn't.
You guys have QA for new versions of Unity that come out?
I have a MarchingCubes algorithm for generating minecraft chunk meshes.
I call it every time a block gets placed/broken. To place/break blocks I just modify a blocks array and re-call the method
Problem is when i place blocks like
⬜⬜⬜
⬜ ⬜
⬜⬜⬜
And then place a middle block then i get a problem where the mesh.triangles is too big cause not enough vertices and the UV array isn't the same size as the vertices array
I guess I'll make this a thread and post the MarchingCubes code tomorrow
Yup! we have some automated tests on our build server. If that passes, we go onto a checklist. 2011 only passed for us about a month ago now.
For a long time it was failing due to broken interface issues with Lists. Issues with Android builds. And issues with SteamVR. Both those all finally passed and we could upgrade.
I'm actually setting up a build server right now haha. We do desktop and android at the moment, are there some examples of automated testing I can get a hold of somewhere?
As my name implies, I'll also be setting up jenkins for CI/CD for the builds
you are on the start of a long and negative ROI journey
you should probably use unity cloud build
you should probably stick to LTS 2021 unless you specifically need better performance in dx12
2022 is really in alpha
it doesn't say its alpha on the hub though
i know
i'm trying to impress on to you it is buggy as hell
I'm writing some code to validate types that aren't following certain rules, this won't execute at runtime so any reflection that can get the job done works.
Is there a way to get which file/linenumber a class is defined in via System.Type?
I'm writing some code to validate types that aren't following certain rules
?
what are you actually trying to do?