#archived-code-general
1 messages · Page 333 of 1
Isn't readable on the phone. That's why the bot message dump sites are better.
All of them are better.
A bit yeah xD
the original dude working on this project left and here i am with this mess
3 resolutions? So the List validResolutions just contains 3 items? It gets the items from Screen.resolutions if the option IsValid and the dropdownOptions don't contain it
Multiplying deltaTime into your velocity is wrong
oh ok
any suggestions on what to replace it with
You will need to reduce the speed to compensate
yeah thats alright
But now your speed variable will make sense as meters per second
ahh
Mouse input should also not be multiplied by deltaTime
Basically the person who wrote this didn't know what they were doing and just thought to throw deltaTime everywhere willy nilly. This is a mistake
And the Lerp part and clamping looks weird to me too.
velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
if(!dashFlag)
{
if(velocity.magnitude > moveSpeed)
{
velocity = Vector3.Lerp(velocity, velocity.normalized * moveSpeed, deceleration);
Not sure if this will give you the thing you want to be honest, this whole code is weird to me.
tysmm ur a lifesaver
yeah im losing braincells trying to understand the code
right now script is different and the bug also
when i click on C# files why do they open in individual windows instead of the same one but as a tab?
Can you make a full screen screenshot of your visual studio?
Hmm, there isn't even a project in here.
Do you open these scripts in Unity?
like they are in seperate windows
yeah i just click the C# icon
pretty sure they supposed to appear here
Did you follow the setup !ide?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
No, you can install visual studio via the Hub, not visual studio code.
And then still, you would need to follow the bot's setup advise.
what is this?? never got it before
That's the editor crashing
how can I optimize physics2d.findnewcontacts?
yeah but its just because of my PC or because code? It happened when i try to upload a game into firebase
Could be almost anything
How should I know what caused it? You provided no context, just a screenshot of the progress bar for the crash
it usually isn't code
code will just cause it to freeze, if you have infinite recursion or something
I couldnt get it either my unity went off and couldnt check the errors on console
and know i open and i can upload without any problem
theres probably a crash log 🤷
Check the !logs to figure out what may have caused it
ok im in the prev-log
now what should i do
but yeah how could I optimize physics2D.FindNewContacts
0x00007FFC7B3AD0A2 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B383081 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B3662F5 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B369532 (FirebaseCppApp-12_0_0) uS::TLS::Context::operator bool
0x00007FFC7B32340C (FirebaseCppApp-12_0_0) uS::Socket::freeMessage
0x00007FFC7B32C8DF (FirebaseCppApp-12_0_0) uS::Socket::freeMessage
0x00007FFD79BF1BB2 (ucrtbase) configthreadlocale
0x00007FFD7BBD7344 (KERNEL32) BaseThreadInitThunk
0x00007FFD7BD226B1 (ntdll) RtlUserThreadStart
========== END OF STACKTRACE ===========
A crash has been intercepted by the crash handler. For call stack and other details, see the latest crash report generated in:
* C:/Users/diego/AppData/Local/Temp/Unity/Editor/Crashes```
well
go to that path
C:/Users/diego/AppData/Local/Temp/Unity/Editor/Crashes
its eating up a TON of the perf
I wish i could see which collider types or which objects had a lot of the calls, since I cant seemingly even with deep profile
in the menu theres no colliders, i crashed when trying to upload
this is my own issue, nothing to do with you
do you have a lot of rigidbodies rattling around?
yes
contacts are computed for collisions, and collisions are caused by rigidbodies
let me try removing collision for the dynamicarms
it wasn't working to keep them from going through walls anyways
yeah that helped
Can anyone help me with my player's movement script? My player walking to automatically moves to the right and I want it to automatically move to the left as well with a and d keys. How can I do it?
rb.velocity = new Vector2(movespeed, rb.velocity.y)
that line is causing it
Thank you, Which one should I delete in void start or update? And I wrote wrong, sorry for that. I mean my player walking auto to right now and i want player walking auto left too(both sides outomatically) If I delete the code you said will it be as I want
simple left right script is typically as follows: (in update)
var Horizontal = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(Horizontal*Speed, rb.velocity.y);
this should work for your purposes
to make it better, make horizontal a field of the class , and update rb.velocity in FixedUpdate
Thank you so much
left clip is without cube interaction, second one with.
Hey guys, there’s nothing that could possibly break from scripts that are not CLSCompliant right?
are you having a problem?
Hey, I have an app in the Google Play Store.
I have installed Unity Ads, which you can skip after one second. However, the skip button is not there for most adverts, it only appears when you click on the advert once. This is bad because many users think that the adverts cannot be skipped and then have to watch the 30-second-long adverts. That's not good, because I definitely don't want that.
Is there any way to set the button to always appear and not disappear?
If not, I'm thinking about not using Unity Ads any more.
I have a weird question, and it's hard to ask because I'm not sure exactly how to word it. Is there a good way to project a mesh onto a 2D surface, to create a polygon which is a silhouette?
I have this thing I want to do, where I take a mesh, and create a pipe with the same profile as the mesh in question, as if they "fit" together.
I've found resources on generating Convex Hulls and Concave Hulls, but they don't seem to be exactly what I'm after.
A hull algorithm will help you. You can do something like this:
- Project each vertex of the mesh onto the surface (the details of this depend on the projection you want. Orthographic? Perspective? etc.)
- Do the convex hull algorithm on the projected points
- The hull is the silhouette
Won't that create an outline which doesn't respect the original mesh, though? Like, if the mesh is of an "X", the result of a convex hull would be a square, as far as I've been able to figure out.
yes a convex hull would be
A concave hull not necessarily, but concave hulls are tricky
If you know the order of the vertices you can create the 2d polygon pretty simply
For example if you have your 3D mesh and you number the vertices, then you can create the 2D polygon with the vertices in the numbered order
concave hulls are simpler when the vertices have a known order
YEah, I'd basically just need a way to find all vertexes that are on the "outline" of the object.
I'm creating 50,000 game objects (2D circles, nothing fancy) but my unity is dying. Every performance video talks about gpu instancing or setting game objects as inactive if not visible. I want all 50,000 game objects (preferably more) on the screen at one time. Is this possible and can gpu instancing be applied here?
50,000 GameObjects is way too many GameObjects
you should not be using GameObjects anymore
switch to something like ECS or some hybrid setup with Compute Shaders/RenderMeshInstancedIndirect etc
okay thanks, i'll take a look
i don't need them to be gameobjects in the slightest, just dots
well, speaking of dots,
hahaha

#1062393052863414313 < home of ECS
you can just use gpu instancing if you dont need any specific logic tied to them
Just switching to manually rendering the circles instead of using tens of thousands of sprite renderers is probably enough
You can directly tell the GPU to draw a mesh at many positions
I highly recommend everyone learning compute shaders and RenderMeshInstanced as a brain enrichment activity.
i read about the latter once so i'm basically a subject-matter expert
also i watched a friend briefly explain foliage via an mspaint drawing
No, but I don’t want to have a problem, and i can’t seem to find information about it so I don’t think I will?
I would only expect this to be an issue if you were interfacing with VB or F# or something
Unity uses unsigned integers in some places, and those are already non-compliant!
i had no idea unsigned integers weren’t CLS Compliant
Well itll probably be fine then
(Well, unsigned chars are ok)
Is it possible to have an editor assembly not get domain reloaded?
With the intent to keep some data around, or what?
I want to have a named pipe communicate between two instances of the Unity Editor and don't want the pipes to close when a domain reload happens
Hey Ho, can Somebody confirm that AudioSource.PlayScheduled() doest work as expected in WebGL even when the documentation says WebGL supports this API. I just want to be sure before I create a bug report lol 😂
Whatever you put into it the AudioSource just immediatly plays without the desired time you put in.
its weird because you can get the DSP Time and all
Audio Mixer stuff I know in general doesnt work with webgl
no clue of the actual reasons
Doesnt have to do with the mixer
ah, ok looking at this method I'd expect it to work then. Don't think I've touched this one before though.
You can use it to create Beat Synced Audio Events
I already got it working but now in webgl it all falls apart...
I thought yeah fine I know that in Webgl stuff like the Audioclip Data isnt that feature rich but well I looked in the docs and worked a way of doing it anyway by just knowing stuff likes samples and frequency in my audio clip
Honestly, this is something I've should have used in previous projects
and AudioSource.PlayScheduled() is marked as working in webgl... well yeah it does but it just ignores the time you put in
For me it sounds like a bug
All I can think of is perhaps some clip settings you have enabled
Just thought I did something wrong... no I just ruled out all thigns
and it's interfering with the method
yeah but what
Unfortunately I'm terrible at audio stuff and is usually the last thing I throw into my projects haha
one WebGL behaviour is that you cant get the clip.samples when the audioclip is not playing, so you just play the clip muted and you can Access this data for you calculations
WebGL often has limitations with anything that's supposed to happen asynchronously
you know, i'm not sure how audio works at all on that platform
also like clip.frequency doesnt exist but well you can hard code 41000 as an int 😂
i guess it's just updated every frame instaed of being a separate thread
(actually, it's just that you can't do multi-threaded C#, i think)
na its definitly not frame by frame
SPECULATION!
yeah 😂
but seriously it just doesnt work at all
its just acts like play
which is not what you want
WebGL doesnt use FMOD it uses native browser calls
So I think I will create a bug report
I just know I've had sync problems with audio in webgl in the past and never felt the need to correct it
usually the comment about the cpu spikes though is handled by the background loading option, no?
which itself is some async operation
what do you mean?
If you don't enable load from background on your clips, you will usually have some sort of sync problems the first time that clip is played in the scene.
Audio is just a lot to load in, so ideally you want to load it all at some loading scene (at the start) of your scene.
yeah but the clip is loaded
and the playscheduled loads the clip anyway
also the function doesnt work with my playsfx on beat stuff
Right, I'm just saying it's one issue I've had with some desync issues, but I guess the idea of this method is it's still not sync'd enough unless you schedule it in a way.
I can spam the sfx how many times I want because playscheduled behaves as the time is just 0
and the time to next beat variable is perfectly calculating
as a double and all
just this stupid playscheduled doesnt work as it should 😂
heck even my Synced Events work
Some fps game I've worked on in webgl the bullet sfx is slightly off and it's something I've been meaning to fix and I guess this should be what I probably need to use.
look at this blog, its a really good starting point
but yeah doesnt matter if it doesnt work
audio is interesting
yeah
it's happening way faster than video
kilohertz, rather than dozens of frames per second
thats why there is the AudioSettings.dspTime as a double
and you use like the PlayScheduled with the dspTime together
for example if I want the audio the be played in exactly 1.2 Seconds I would add the current dsptime together with 1.2 and put it in the PlayScheduled
you can use this to stitch together audio sources like an Intro part and a looping part, and then you can calcualate the beats and bars and know exactly when they occur and do stuff with it
like play sfx on beat
Or like fire animations, tough these have to be on frames again
So yeah you can recreate Hifi Rush 😂
but not in WebGL I guess 😭

For a rhythm game though, you probably don't want to use dsp time, you still need frame time to sync up audio with graphics. But well that's besides the point, if PlayScheduled doesn't work as intended then that basically ruins the whole thing.
Na thats not necessary, audio to be synced is more important then the visuals, we humans can deal with alot of Audio Visual delay actually so using Events in an Update is fine
IEnumerator LoadSceneCoroutine(string sceneName)
{
transition.SetTrigger("Start");
yield return StartCoroutine(WaitForRealSeconds(transitionTime));
//yield return new WaitForSeconds(transitionTime);
SceneManager.LoadScene(sceneName);
}
IEnumerator WaitForRealSeconds(float time)
{
float elapsedTime = 0f;
while (elapsedTime < time)
{
elapsedTime += Time.unscaledDeltaTime;
yield return null;
}
}
The transition is the animator. I am trying to make the transition use Time.unscaledDeltaTime so that it continues to run even when the game is paused, which is when the timescale is set to 0. However, this doesn't seem to be working.
WaitForSeconds doesnt work with timeScale set to 0 maybe WaitForRealSeconds doenst work aswell 🤷🏻♂️
Eh I very much disagree with that for a rhythm game, but I suppose it depends on the kind of rhythm game you are working on. Audio visual sync is a huge known problem in the rhythm game genre and that's why lots of games offer an offset settings to allow players to manually adjust and compensate for hardware delay themselves. The issue is even more pronounced on mobile.
yeah but the key is more to have the visual part seperated from audio and input
If you press on beat then it still counts and the visual follows
Any suggestions on how to fix this?
dont use TimeScale 😅
I'm not sure how to pause everything in the game except for 1 thing without using timescale
try using something different then WaitForSeconds
a while loop will work
you need to create you own timer
Use a bool from a singleton and do an early return when the bool is true on everything you want to pause
And in coroutines loop while doing nothing with a while
Can you ellaborate? I'm dont quite understand
TimeScale = 0 stops the Update Routine but not a Couroutine, but WaitForSeconds will stop working
Which part? Do you know what a singleton is?
I guess its the same with WaitForRealSeconds
I know what a singleton is
This is not true.
Update runs once per frame
It doesn't matter what the timescale is
There is already a WaitForSecondsRealtime class you can use here
Ok, so that singleton has a bool.
Everything you want to pause checks the state of it.
If the bool is true (game is paused), then return
if (PauseManager.instance.isPaused) return;
well if you dont produce frames then ... 😂
The timescale has zero effect on the framerate.
There are way too many gameObjects and scripts in my scene though. I am trying to look for an alternative approach
Well, the alternative is timeScale = 0
I think its late here, Im confusing myself with fixedupdate lol
but the point stands WaitForSeconds breaks 😂
FixedUpdate also runs 50 times per real second. nope!
or whatever you put into unity
I don't see anything wrong here.
One important thing, though, is that your animator might be stopped
I used Fixed Update to get more precise inputs in a 30fps game 🫠
Consider using Unscaled Time if you want to ignore the timescale
oops, that was not a very useful screenshot
Where do I find this window?
It is on the Animator
this is the inspector for the Animator component
I can't find it
That's not the Animator component
It is unfortunately named, but that is the Animator WINDOW. The component would be on a gameobject, viewed via the inspector window
It works now after I adjusted the time scale on the animator. Thanks!
https://docs.unity3d.com/ScriptReference/Time-timeScale.html
It says it's not called if 0
Interesting. I don’t know it abruptly stopped at zero
That’s good to know!
Actually, since the number of times it’s called per frame depends on the timescale, that implies it runs 50 times per in-game second
That sounds right, since I remember having to adjust fixedDeltaTime to update physics more frequently during slow motion
And that also makes sense given that fixedDeltaTime will still be 0.02 (by default) no matter what the timescale is
If it ran at 50hz in real time, you’d move too fast in slow motion
Hey! Im having issues getting a collider to react to a trigger. No matter what ive done, (adding/removing rigidbodies, messing with collider and rigidbody settings, double-checking tag names and OnTriggerEnter scripts, checking the physics matrix) nothing seems to work. I have other objects in the scene that respond to it so I'm not sure why this one specific object type isn't reacting.
both must have colliders, one must have a rigidbody, one must have IsTrigger on the collider
thx lol
Is there a wrong way to write a command in the command pattern? How complex should a command be on average?
I'm making a tower defense and would like to have a tower that boosts other towers within range. I'm trying to use OnCollisionEnter2D to find when a tower is within range, but this TANKS the framerate, I can only have 1-2 of these towers on screen while staying above 60FPS. Any suggestions?
https://pastebin.com/Qt6QbyT4
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I have every other tower using Physics2D.CircleCastAll almost every frame to find a target to shoot at and that barely affects framerate at all, but I was having a hard time using that in this situation because those towers only have one target at a time, whereas I want these ones to be able to affect every tower within range
Dont understand why it would tank. It should only happen once anyway, but you should be using trigger colliders, not collision
Ideally, CircleCast the buff towers too every few frames.
I think the best way to do it though is have some manager that holds the radius/ranges of buff that when a tower is place it looks up the table of these buff towers and subscribes to them, but that's probably a lot more work.
The minimum complexity required to satisfy your requirements
It wouldn't be a circlecast it would be an OverlapCircle
oh yeah overlap circle because circlecast can actually miss detection it's at
It's just conceptually wrong to use circlecast
Thank you both I will look into this
I usually use overlap in conjunction with casting if I were to use it
okay well the buffing part of it is working but I still can't figure out why it's tanking the frame rate. I can put down 4 of the ant tower without seeing anything change but 4 of the omniflower and it just destroys the performance. Right now both towers have the same components attached to them. Frame rate is bottom right of the game view
The omniflower isn't even doing anything anymore, I have the towers using overlapcircle to find it instead of it using ovelapcircle to find the towers
Time to pull out the profiler
Certainly if you're not using the Non-allocating version that will be part of the problem
I'm trying to spawn rows an object that increases by 1 in each row but I need to have them aligned in the middle. It stops so theres something wrong with my formula for getting the X position.
{
var spikeRow = CreateRow(_rowMultiplier * i + 1);
float currentX = -spikeRow.Length * _rowSpacingX; // Find the starting point
for (int j = 0; j < spikeRow.Length; j++)
{
spikeRow[j].transform.position = new Vector3(currentX, 0, i + (i * _rowSpacingZ));
currentX += spikeRow.Length * _rowSpacingX; // Add Onto the starting point
}
yield return new WaitForSeconds(_spikeRowInterval);
}```
Do you have any good resources on it?
id stick some break points on code that should only be executed once
I have a theory and it seems to be accurate. When I remove the second circle collider that I'm using to detect boosting towers the frame rate goes way back up. I think the two circle colliders are constantly colliding with each other, but telling them to exclude each other's layer doesn't seem to fix it
I can only imagine you've some exponentially growing logic for each tower placed
are you sure you're using OnTriggerEnter and not collision
Is your spacing supposed to be increasing, or are you just trying to offset to the left each row? You've two different ideas here it seems
Thats actually a good question, the spawn between should be the same
in that case your space shouldnt increase, only the offset
I had the collider I was using for finding boosting towers also colliding with the dirt objects in the background in the collision matrix so it was generating a bunch of uneeded overlaps. Thank you everyone for the help
So i removed the multipler and am getting this. What I need to do now is figure out how to have them all end up at the center
Right, which should just be a constant spacing value
only thing changing each row iteration is the offset
Struggling a bit atm but does there need to be some kind of check if the row size is an odd or an even number?
how would I export an image of a grid layout of sprites, for the purposes of exporting a deck recipe?
i made a simple spider-like entity basics , but when i tried make it stand up with rigidbody's addforceatposition it had this weird bounce and rotationing, how can i make it so it dont do that but still allow rotation?
why not just use add force? Add force at position applies torque on the object, which is causing it to spin in your case.
I want it to spin based on the environment
like if it's falling of a ledge it spin or if it's on a slope it gets more angled
how do I make my scene darker and make objects further away less visible?
Use lighting
this is what i have but i can still cant figure out how to make farther objects less visible
well its the boxs that arent working
You're using a 3D light
You need to use 2D lighting
oh
BTW you need to be using URP for that
wheres 2d lighting?
Linked you to this #archived-code-general message
I'm looking for opinions or advice.
I have a method spawns objects. It can spawn enemies, items, chests, etc. Currently I have a separate method for each object type, but it's ineffiecient. I would rather have a single method that returns one object type instead of returning an enemy, or an item, or a chest, etc.
Not sure what the best way to go about this. They are all scriptable objects, so I could potentially have all these objects inherit a class called Spawnables, and have Spawnables inherit scriptable object so the objects still get to stay as scriptable objects. But I don't know if it would make sense to have an empty base class that only exists to bundle all the objects together as a single type.
Another option I think is to create a new class that contains every spawnable object as properties, and if the spawn method chooses an enemy, insert the scriptable object into that new class that contains all spawnables and return the new class.
I'm leaning toward the inheritance portion but I don't know if it's right for me to make an empty base class that only exists to tie all the objects together by a single name. What do you guys think?
What's wrong with having a method for each spawning type? It's less ambiguous, otherwise you're probably doing some comparison somewhere if you're wanting to combine it all.
If the spawnable class is just empty, does it really need to exist? It sounds like your method's logic can spawn any SO at that point.
You could implement spawning logic on the SO itself, assuming it's supposed to be bundle with one specific type. I do this for stuff that I don't usually object pool, but you can probably throw that logic inbetween.
The spawns are based on random chance, and in a specific order. So I get a random number, if it's lower than X then an enemy does not spawn. Then I do the same for an item. Then I do the same for a chest. And it keeps going down the path for every other object type. The problem though is I'm introducing another class that needs to spawn something in as well, so I was hoping it could return me a single object type instead of me having to call all those methods.
ItemSO.Init() -> Returns Item<ItemSO>
Maybe nothing is wrong with having a separate method for all of them and I'm trying too hard to optimize, but thought I'd get more insight first.
If I spawn an enemy usually I am doing calls like
``` because I'm usually object pooling everything
It will also help if you can show your current code.
Here's my code:
Instead of having another class that wants to utilize the spawning logic that goes if (RollForRareEnemy != null) else if (RollForChest != null) else if (RollForPowerup != null) etc. I was hoping to call just one method to get one of these objects.
Or maybe not, maybe what I'm thinking doesn't make sense and I should just keep it this way.
public float walkSpeed = 4f;
public float maxVelocityChange = 10f;
private Vector2 input;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate(){
rb.AddForce(CalculateMovement(walkSpeed), ForceMode.VelocityChange);
}
void Update()
{
input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
input.Normalize();
}
Vector3 CalculateMovement(float speed){
Vector3 targetVelocity = new Vector3(input.x, 0, input.y);
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed;
Vector3 velocity = rb.velocity;
if (input.magnitude > 0.5f){
Vector3 velocityChange = targetVelocity - velocity;
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
return (velocityChange);
}
else {
return new Vector3();
}
}
Is this considerd a good way of making player movement? first time that i did it my self
Not seeing the scriptable object idea here as it seems like you've got them as prefabs, which is fine.
That's a whole 'nother can of worms I'm not ready to discuss. lol
But basically a prefab grabs the scriptable object (enemy for example) and uses all of its logic and stats.
Right, if there's something you did want to minimize, it's using a single prefab type which you build from SOs. That's fine and allows you to reuse them instead of outright destroying.
if it works for your game, sure.
as for spawning them. It's probably not that big of a deal if you did want to have a central instantiation method somewhere, but you'll eventually be doing some comparisons somewhere in that method.
Are these the code you want to reuse?
numPadSlot.EnemyData = Instantiate(rareEnemy);
numPadSlot.ObjectType = ObjectType.Enemy;
changeSprite.sprite = numPadSlot.EnemyData.sprite;
if (!string.IsNullOrEmpty(numPadSlot.EnemyData.spawnSound))
{
AudioManager.Instance.PlaySound(numPadSlot.EnemyData.spawnSound);
}
If so then yes, you can extract them out. They are pretty much all repetitions.
Yeah, it's true.
because you need to know how these SOs are assigned to that object so a type will be needed somewhere.
I wanted to reuse everything up until line 41. But then I'd still have to make a separate method for each object type.
But it's looking like somewhere I'm still going to have to do some kind of comparison like Mao was saying though so I may end up keeping them as separate methods.
Are you talking about reusing the Roll* methods, or reusing the repetitive same code of if (rolled != null) { do the spawning } for every type of roll?
Both.
oh yeah you can probably reuse all that if it's not specific only to the enemy.
For the latter, you can very much rewrite it as:
EnemyData Roll()
{
var rareEnemy = RollForRareEnemy();
if (rareEnemy != null)
return rareEnemy;
var chest = RollForChest();
if (chest != null)
return chest;
// ...
}
void Spawn()
{
var rolled = Roll();
if (rolled == null)
return;
numPadSlot.EnemyData = Instantiate(rolled);
// rest of the stuffs etc
}
Now at least you are not repeating the same spawning logic for every roll method.
for this:
RareEnemy rareEnemy = RollForRareEnemy();
Do you roll for every type of object you want?
If the rare enemy spawn succeeds, then nothing else spawns. So that means I won't roll for the others. Not sure if that answers your question.
public enum UnitTypes
{
Enemy,
Item,
}
public void Spawn(int digit, UnitTypes unitType)
{
if (NumPadSlots.TryGetValue(digit, out NumPadSlotData numPadSlot))
{
//It also selects the enemy type/appearance
SpriteRenderer changeSprite = numPadSlot.ObjectSpawnContainer.GetComponent<SpriteRenderer>();
Unit rolledUnit = RollForUnit(unitType);
if (rolledUnit != null)
{
numPadSlot.UnitData = Instantiate(rolledUnit);
numPadSlot.ObjectType = rolledUnit.GetType();
changeSprite.sprite = numPadSlot.UnitData.sprite;
if (!string.IsNullOrEmpty(numPadSlot.UnitData.spawnSound))
{
AudioManager.Instance.PlaySound(numPadSlot.UnitData.spawnSound);
}
}
//Other logic in a similar fashion
}
}```
one idea
Enemy, Item would be derived from Unit. So, you'll eventually have to check for the type which it seems like you do with ObjectType
I'll play around with your suggestions. I have to go now, thank you Burrito and Mao!
If you have a ton of rolling methods and even writing var x = RollForX(); if (x != null) return x; is getting repetitive, you can further clean it up:
Func<EnemyData>[] _rolls =
{
RollForRareEnemy,
RollForChest,
// ...
};
void Spawn()
{
EnenmyData rolled = null;
foreach (var roll in _rolls)
{
rolled = roll();
if (rolled != null)
break;
}
if (rolled == null)
return;
numPadSlot.EnemyData = Instantiate(rolled);
// rest of the stuffs etc
}
Now if you have new things to roll, just add that to _rolls and don't need to touch any of rest of the code.
(Presumably your roll methods are quite different from each other that they can't really be made DRYer)
Hey, I have an app in the Google Play Store.
I have installed Unity Ads, which you can skip after one second. However, the skip button is not there for most adverts, it only appears when you click on the advert once. This is bad because many users think that the adverts cannot be skipped and then have to watch the 30-second-long adverts. That's not good, because I definitely don't want that.
Is there any way to set the button to always visible and not disappear?
should i make indivual scripts or just make a HUGE switch statement to control the functionality of my enemies
Implement according to your designs and worry about optimization later. Food for thought: Undertale's dialogue system was managed with a single massive switch.
https://www.reddit.com/r/programminghorror/comments/10dgoxm/til_that_all_of_undertales_dialogue_is_handled_in/
one switch?? that sucks
I have some weird problem when unity crashes for some reason when I try to add a component to some game object
I am working on an editor tool and I add the script in prefab mode, I suspect some reimport magic happens and it crashes unity
The worst part is that I can't read anything understandable in the Editor.log
Can somebody help me diagnose or tell me how I can debug an editor crash?
that's my editor log
pretty wild, but seems like adding components with mouse click works, but clicking Enter when "Add component" popup with selection is present crashes the editor 🙃
Report a bug!
hey i want to create a scriptable object via the menu (because I have to get rid of the editor code to build)
but whenever I create the scriptable object, it doesnt add its script...
When i try to add it manually i get an error.
public class FetchColors : Editor
{
[ColorPalette]
[Tooltip("This is just to quickly change the actual palette!")]
public Color Color;
static ColorPalettes SO;
[MenuItem("MyTools/FetchColor")]
public static void FetchColor()
{
var lastEntry = Sirenix.OdinInspector.Editor.ColorPaletteManager.Instance.ColorPalettes.Count - 1;
var colorPalette = Sirenix.OdinInspector.Editor.ColorPaletteManager.Instance.ColorPalettes[lastEntry].Colors;
SO = (ColorPalettes)CreateInstance(typeof(ColorPalettes));
SO.Colors = colorPalette.ToArray();
SO.name = "BrickColor";
SO.AddComponent<ColorPalettes>();
AssetDatabase.CreateAsset(SO, $"Assets/ScriptableObjects/{SO.name}.asset");
AssetDatabase.SaveAssets();
}
}
[CreateAssetMenu(fileName = ("ColorPalette"), menuName = "SO/ColorPalette")]
public class ColorPalettes : ScriptableObject
{
public Color[] Colors;
}```
This is very confusing
Why are you doing AddComponent at all here
This is not a component
It's a ScriptableObject
And you seem to be trying to add itself as a component to itself???
That's a field
because i need it to have a script to reference it
Huh?
this object is supposed to be referenced by my runtime component
i can reference it as a scriptable object but then i have no access to the color list
well is the color list public
as you can see in the code, it is
so then you can just access the array from a reference hten
no i cannot, since the object seems to be created without the script attached
recreate the object from the create menu
i need to delete the addcomponent line for that
i don't understand your problem
its a scriptableobject
The type is ColorPalettes @subtle path
That's the type you reference it as
Because that's what it is
Sorry went in a tunnel
you never add component it
but the script that needs that reference, cannot find the colorpalettes script, because its in the editor folder
dont put it in the editor folder then
then don't
If this is a runtime thing then you can't do this anyway
it has to be in the editor folder, because i cant build my project otherwise
So what you're saying is this is all a giant XY problem
we're at Z I think
dude im already many steps in the problem lol
yes
so walk back to the original problem
not your attempted solution
your attempted solution makes no sense
i have no better
Explain your original problem.
You're going down the wrong path for many steps
The problem occurs when people get stuck on what they believe is the solution and are unable step back and explain the issue in full.
oh hey a typo
The problem you're having is trying to include some editor things on a runtime script. This can be done usually with preprocessor directives
Or at worst splitting the editor and non editor parts
yes: you can use #if UNITY_EDITOR to cut out the part that should not be included in the built game
doesnt work for my problem
I don't even know what your problem is because you've refused to tell us about it
you have only explained your attempted solution
im not refusing, you are just overloading me with solution suggestions, i dont even had the time lol
also if you do the #IF UNITY_EDITOR thing you need to do the same for editor using statements
if you don't have any time to explain your problem, we don't have any time to help you with it
if you could chill at least a minute, i could think about how to explain this problem
so this was the solution, which i got working rn. it didnt work before because I was referencing the script wrongly.
so thanks for your help, guys
Hi, I have 2 locations on the screen and I want to stretch a square between them, which will actually be between one location and the other. how can i do that?
So i have this method for grabbing an item that uses scriptable objects to do it. In another script, the method is called by getting the scriptable objects name, value, and a type. however, i want to just get the scriptable object itself and then use the method to pull those values out instead of having to do it in the other script to make it easier and more reusable. how do I check what type of scriptable object something is in the overloads?
public void GetItem(string name, float value, string type)
{
Debug.Log("Attempted to grab item: " + name + "\n" + "With attached value: " + value);
if (type == "Weapon")
{
weaponsDict.Add(name, value);
}
else if(type == "Accessory")
{
accessoriesDict.Add(name, value);
}
}
wouldn't something like type is ScriptableObjectName so work?
i want it to be the scriptable object itself, so i can pull values from it
id assume it means i have to make overloads of the scriptableobjects themselves, like i have 3 right now, "Weapons", "Accessories" and "Chest" so id have to do something like
public void GetItem(Weapons weapon, Accessories accessory, Chest chest)
but is there any way I can make them optional, so i can put in just one overload?
so i dont have to make the other ones null every time
when i call it i mean
If i was opening a chest, id call it like GetItem(null, null, chestObject) with that
you could have a base ItemScriptableObject and then have WeaponScriptableObject : ItemScriptableObject, then have the method take in ItemScriptableObject and have a switch statement for the different types?
that makes sense, but im not so great with encapsulation yet as i just learned it
ill see if i can figure it out later
You can also use interfaces with this, define some method GetItem in the interface and have your scriptable object inherit from it, then have your sciptable object implement it for each type
Should I use a tween/lerp for my ADS or an animation? There will be multiple guns btw.
Sure
You didn't ask which one. Putting or between the choices would have made it a question of which
Either works
Yeah I did, I said Should I use a tween/lerp for my ADS OR an animation?
How can I convert a location on the canvas to a real world location?
That doesn't make much sense
Do either
Your choice
Both work
okay
I read it as asking if you should use a tween/lerp for ads
And also asking if you should for animation.
Apologies for my confusion
Hey! I know this question could be answered in different ways based on a person, but how can I setup SCALABLE interaction with objects in terms of architecture?
I'm following "unity way" with more decoupled components as it's core + general good practices in my project, but I'm stuck with interaction system, because I can't decide how to do it more "properly" and scalable
Like, I've tried component based approach and inheritance tree, but I didn't like it and it's quite a mess for something that is just not "fire and forget" interaction (like doors or pickups)
So, how to do it in a "pro way"? Can someone share a good example of that system or just point me in the right direction?
Im currently making a script to spawn ores randomly on my terrain but it keeps spawing it bellow the terrain how would I get it to "snap" to the top layer? This is the segment im guessing neededs to be edited. Vector3 GetRandomTerrainPosition()
{
// Initialize combined bounds
Bounds combinedBounds = new Bounds();
// Calculate combined bounds of all terrain tiles
foreach (Terrain terrain in terrainTiles)
{
combinedBounds.Encapsulate(new Bounds(terrain.transform.position, terrain.terrainData.size));
}
// Generate random position within the combined bounds
Vector3 randomPosition = new Vector3(
Random.Range(combinedBounds.min.x, combinedBounds.max.x),
0f,
Random.Range(combinedBounds.min.z, combinedBounds.max.z)
);
// Get the terrain height at the random position
float terrainHeight = 0f;
foreach (Terrain terrain in terrainTiles)
{
if (terrain.terrainData.bounds.Contains(randomPosition))
{
terrainHeight = terrain.SampleHeight(randomPosition + terrain.transform.position);
break;
}
}
// Set the spawn position to the sampled terrain height
Vector3 spawnPosition = new Vector3(randomPosition.x, terrainHeight, randomPosition.z);
return spawnPosition;
}
}
Thanks you!
@solid timber !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thanks
@waxen blade sorry I had no idea. https://paste.ofcode.org/nqnGq2u7pCygqgXrrGA4Rr
Im currently making a script to spawn ores randomly on my terrain but it keeps spawning it bellow the terrain how would I get it to "snap" to the top layer? Above is the code segment I beilve is causing the problem. Thank you for any help!
my first assumption is its spawning at your ore's center pivot ? so half under and half over ?
like where below the terrain do you see it spawning
Its all at one layer im guessing its the 0 layer on the y axis
can you send screen shots here?
Almost never use inheritance, just make reusable components, with interfaces.
So if you had pickables, have a IPickable interface that all your pickables implement.
That's the gist of it.
(and the interface part is optional, too)
my design is all composition-based
At one point I had an interface for two similar components. I wound up factoring out common behaviors into other components, merging the two original components, and discarding the interface 
I do use interfaces a fair bit for non-Component types, though
The way I learned to do things is start with a behemoth script, and only abstract out logic when it becomes obvious that it's useful. Though this is only meant for gameplay scripts. I usually always do audio, animation, and UI in scripts that I can delete and the game will still run fine.
you need to subtract the terrain's position before calling SampleTerrain
actually...no, you need to do neither!
its input is in world space
That's sort-of what I wound up doing
except I wound up going so far with the behemoth component that I got mad and did a complete rewrite
Also, you should add a Debug.Log message for when you correctly find the terrain height
that'll help you tell if it's working or not
(and the proper way to get to terrain space would be to do terrain.transform.InverseTransformPoint(worldSpacePos), in case you need to do that later)
gameManager.SwitchState(gameManager.SumoState);
I'm currently using this code to make my game manager switch state to the "gameManager.SumoState". I would also like it to switch to other states like "gameManager.LobbyState", or something else that starts with "gameManager.". Is there a way to use a variable by name or similar so i can just put a variable after "gameManager." and it will use that variable?
Is that an enum ?
no, dont think so
Accessing fields by name would be reflection
and that usually means you're doing something wrong
yea i wouldn't be suprised :/
How are you deciding which state to go into?
Presumably there's a reason you aren't just writing gameManager.FooState or gameManager.BarState
you can put the state itself into a variable
unless gameManager.SumoState is constantly changing
in that case, if you have a fixed set of possible states, I'd create an enum type and give gameManager a GetState method
ah okay, that makes sense
public enum StateKind {
Sumo,
Foo
}
// ...
public State GetState(StateKind kind) => kind switch {
StateKind.Sumo => sumoState,
StateKind.Foo => PickCorrectFooState()
};
maybe like that
i used a function at the end to show that you could have more complex logic
this is a switch expression. very handy for picking between things based on an enum value!
ah perfect, i haven't used an enum before so this is great, thankyou
K&R heathenry
That's fair enough
I'm having trouble matching heirarchal transform positions. If i place a game object directly in my scene, and place an independent game object within my scene. Will these match or will i require an overall parent to match transformation positions?
i don't understand the question
if you give them the same world position, then they'll be in the same place
gameManager.SwitchState(gameManager.GetState(GameManager.StateKind.Lobby)); Is this the right way to be using the enum?
If they have the same parent, then giving them the same local position will also put them in the same place
Right -- and maybe you could simplify that to SwitchState(GameMangaer.StateKind.Lobby)
You can set the position of one object to another in code. You can also ensure an object follows another object by making it child to it.
as an overload if you sometimes need to let other classes pick a state directly, or as the only option if GameManager is the only one that can pick states
the former might look like
public void SwitchState(StateKind kind) => SwitchState(GetState(kind));
public void SwitchState(GameState state) {
// whatever logic goes on in here
}
and the latter would be near-identical; you'd just make the second method private
Odd... These are not in the same position...
i hope the images are ok to post here.
the camera holder is in the same position as the player
that tells you very little about the camera's position
Oh. Setting local position to zero matches its parents position correct?
Camera holder does
i presume the camera is one of them
That fixed it thank you! Completely forgot to send children to zero.
Hi! A player sent a bug report in my game that they accidently shut down the power while playing, and after booting back up, the keyboard and mouse were unresponsive.
How do I begin to diagnose this, does Unity generate error log files somewhere?
Well, actually, I know there's this log file. I'm tempted to start by asking them to share that, does that make sense? Or is there something else I'm not aware of?
yeah that's basically the only log file unity will create on the client device. other than crash reports, but if it wasn't an actual crash then there won't be one of those
I'm hopeful Unity's Input system throws some errors logs there at start-up
but idk
Okey, so that's the one. Thank you!
Im looking for some ideas on how to handle "surface contact" (ex: walking on or having a bullet impact metal, wood, etc, an object falling/hitting that surface, etc) - my first idea was to use a raycast to check the texture or material name, but that feels like it wont scale well for my use case - my second idea was to use a SO that holds a list of materials that should produce specific sounds, though im worried this will also be difficult to manage with more content, any ideas on alternative approaches I could look into or does the SO approach maybe make the most sense for my use case?
Okay, I'm not sure where to place this question, so I'll just place it here.
Are there any other developers that are using EditorGUILayout.EnumFlagsField with very inconsistent results whenever it's being used multiple times for the same Enum type? (not variable!)
If you would like to answer this, please Reply to this message or @ me.
Thank you! ❤️
_Ref: https://docs.unity3d.com/ScriptReference/EditorGUI.EnumFlagsField.html_
To clarify it a bit more, whenever I'm converting it to a Unity supported type, like an integer, I'm receiving incorrect results.
I'm using Unity 2022.3.16f1
UPDATE: I'm gonna try to reproduce it in an entirely clean project and if it's still happening, I'll report it as a bug.
Yeah. It's a bug. I'm gonna report it, lol.
Hey !
How can i do an reference specific to the gameobject "player" who we control and not another player ?
the gameobject spawn so i can't do a simple reference and i can't link the script
@gray mural Maybe you know ?
don't ping people into your questions, but there are many ways to get a reference to that object
I ping him cause he help me and he suggested I reply to his last message every time but here is different so its same between reply and ping ^^'
[Do Not] @’ing or replying to people who aren’t in the conversation.
ok
why is my transform.rotation.eulerAngles.z returning only 0
okay, correction: I have a child reference so it's childTransform.eulerAngles.z
Euler angles are meaningless when taken in isolation
so then how do i read the z rotation value
Unity doesn't store rotation in XYZ angles, so there is no Z rotation. It does store angles in the editor, just to make it easier for you to edit it. But that's lost in play mode when it gets converted into another format.
yes, you can get very surprising results
like a slight rotation completely changing all three euler angles
yeah i noticed that
The Z axis should be the best behaved, at least, since the Euler angles represent rotations around your Z, then X, then Y axes
Maybe describe what game mechanic you're trying to create, you might be able to just store your own values for what the z rotation should be.
I'm trying to make a door swing open. I thought i could just coroutines but it has no idea when to stop since it cant read the angle
so i guess i'd just have to get the angle through trig, right?
I'd add two Quaternion fields: one for the closed state, one for the open state
You can then use Quaternion.Slerp to move between the two
float t = 0;
while (t < 1) {
t = Mathf.MoveTowards(t, 1, Time.deltaTime);
transform.rotation = Quaternion.Slerp(closed, open, t);
yield return null;
}
an example
this takes one second to open the door
or, if you want to use local rotation
transform.locationRotation = ...
You can right click the rotation in the inspector and hit "copy as quaternion", then paste that into the closed/open fields
ohh
okay yeah that makes sense
i was initially using slerp but I think I was just doing it wrong
thank you very much though
If you want to adjust the motion of the door, you can throw in an AnimationCurve
float remapped = curve.Evaluate(t);
transform.localRotation = Quaternion.Slerp(closed, open, remapped);
could be handy for making it dramatically swing open
You might be able to just use an animation too
yeah but i figured I'd have more customization via script
Hey, I'm trying to draw a line over time, but it keeps drawing a line from the origin, which I don't want.
This is my code: https://hastebin.com/share/locofufovi.csharp
Any ideas? :)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Have all positions default to the first position rather than be at (0, 0)
You'd at the very least get a complete shape between iterations.
for(int i = 0; i < _lineRenderer.positionCount; ++i)
_lineRenderer.SetPosition(i, _vertices[0]);```
It looks like you've got a single point in the middle but I'm assuming you've got every point in the middle prior to setting the point position.
In the editor i have only the default settings for the line renderer positions, so 2 positions both at (0,0,0). Changing them doesn't do anything as the script overrides it completely.
I tried putting your code snippet directly after initializing the vertices array, but still the same problem.
Show your updated code
Reminder that changes will not take effect until after you've saved the script.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Well.. the position of vertex zero before being assigned is at (0, 0)
So assigning (0, 0) to each position at (0, 0) would make little difference.
You'd want to assign it after establishing the first - aye.
the origin vector shows up at the second segment
Not sure what's going on but if it's set to index 0 of the vertices array, all points should start at the first position
You could probably skip the first position in the coroutine unless you're wanting to wait for it to move to it's default position.
Looks satisfactory, other than the end.
Could probably terminate one position sooner to remove the last behavior - the final point is already at the initial point.
like this you mean?
Looks good unless your intentions were different
it looks kinda ok, but i'd still prefer for it to be simply "drawn"
i still don't understand where this "extra line" is coming from
Then have all points set to the target point in the second coroutine
Imagine 5 points: 0: (0, 0 1: (0,0) 2: (0,0) 3: (0,0) 4: (0,0)//5thInitially you'd only change one point at a time so every other point was in the center (you're not adding points but simply changing their position)
But now you've got every position at the original point (vertex 0) so every other position after the ith point would be at vertex 0's placement.
If you're wanting to make an illusion of adding entirely new points, you could set every point from the current to the end to be at the latest point.
private IEnumerator DrawLineSegment(Vector3 start, Vector3 end, float duration, int endIndex)
{
float timer = 0f;
while (timer < duration)
{
timer += Time.deltaTime;
Vector3 newPosition = Vector3.Lerp(start, end, timer / duration);
for(int i = endIndex; i < _lineRenderer.positionCount; ++i)
_lineRenderer.SetPosition(i, newPosition);
yield return null;
}
for(int i = endIndex; i < _lineRenderer.positionCount; ++i)
_lineRenderer.SetPosition(i, end);
}```
Programming on mobile discord, expect mistakes.
Thank you! :)
very impressive - I'll have to stare at that code for a bit
is there some sort of karma system here or something?
Nope, everything's voluntary. Glad everything's working 👍
It's a pretty neat script now. I put it here in case you wanna use it: https://hastebin.com/share/uqavufosoc.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
A minor refactor/optimization would be to use SetPositions (plural) rather than SetPosition (single).
Set Position: https://docs.unity3d.com/ScriptReference/LineRenderer.SetPosition.html
Consider using SetPositions instead, if setting multiple positions, as it is much faster than making individual function calls for each position.
Set Positions: https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
This method is preferred to SetPosition when setting all positions, as it is more efficient to set all positions using a single command than to set each position individually.
You'd cache all of the changes and set the positions in a single batch - added a cache for the line renderer (an array) and modified the set position lines to not immediately make changes to the line renderer but to only do so after all positions/changes have been set https://hatebin.com/jjdhgnirvb
similar to how you can combine mesh and draw them in draw call,
can thesame be done for sprites, while maintaining sprite individuality? or while I just need ALOT of sprites renderers when putting many sprites on a map
so i have my code and for some reason i want the bullethole effect to not show when im in my reload animation. i have been following a tutorial and when this problem occured i have been searching for a solution for days. when i have my reload animation playing and i click the bullethole effect shows and i dont want that. https://pastebin.com/xjSFJCTD
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What's the bullet hole effect? If they're some objects in the scene, perhaps simply set them inactive or disable their renderer component.
its a prefab
So they're objects that are instantiated in the scene?
yeah ima send you a video rq
And you don't want them visible when reloading?
yes
Cache every bullet hole instantiated and simply set their renderer component to not be enabled when reloading.
the prefabs have this. i dont see a render component
Scroll down just to be sure?
Acquire the particle system component and probably stop it
https://docs.unity3d.com/ScriptReference/ParticleSystem.Stop.html
wait do i put these somewhere in my code? ParticleSystem.Play(), ParticleSystem.Stop()
ohhh
You could pause them as well if you don't necessarily want to stop em.
i tried. i dont know what im doing ive never done this before
Cache the bullet holes:```cs
private List<ParticleSystem> bulletHoles = new List<ParticleSystem>();
[SerializeField] private ParticleSystem bulletHoleGraphic;//No point in referencing it simply as a GameObjectcs var bulletHole = Instantiate(bulletHoleGraphic, rayHit.point, Quaternion.FromToRotation(Vector3.forward, rayHit.normal)); bulletHoles.Add(bulletHole);cs
private void Reload()
{
reloading = true;
shooting = false;
// Play reload animation
if (gunAnimator != null)
{
gunAnimator.SetTrigger("Reload");
}
Invoke("ReloadFinished", reloadTime);
foreach(var bulletHole in bulletHoles)
{
if(bulletHole)
{
bulletHole.Stop();
}
}
}``````cs
private void ReloadFinished()
{
bulletsLeft = magazineSize;
reloading = false;
foreach(var bulletHole in bulletHoles)
{
if(bulletHole)
{
bulletHole.Play();
}
}
}```This would stop the particles when reloading and play them again after finishing the reload.
oh ok ty
its got some errors that i could fix
You'd normally post the error along with any questions/concerns that you've got.
oh ok 6 errors though but i will fix them. if i got some questions i may ask later on
these are the errors i have an i thought i could fix them but i cant
List requires the System.Collections.Generic namespace https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-8.0
ohhhh
You should be able to right click List and add the namespace.
As for bullet hole graphics, I simply changed it's type reference that you had originally (GameObject) to ParticleSystem and made it private-serialized.
If a component class is addresed, then the object that was created from that class can affect the component attached to the target game object ?
I'm sorry im dumb and new at unity ;_;
I just didn't catch what you were trying to ask/verify.
I'm assuming you're suggestion something related to if an object is referenced.. (it could be a prefab or scene object)
If I have the myRigidbody object created from the class Rigidbody2d, then I can use it to change the Rigidbody2d component in the Unity window ?
what does this even mean
That means you've got two bullet hole graphics variable in your class. Likely your original GameObject reference and the new Particle System reference I posted above. Where they were meant to be the same reference.
what are "objects" in terms of being an "instance of a class"
and i can use "new" to make a new instance of a class?
So the field that you've got up top would simply be referencing some Rigidbody2d component or null by default. You can set this component in the inspector or by code (awake, start etc) - preferably in the inspector.
Calling the public methods on that instance would make changes apply to that instance.
So if you've referenced the bird in the scene with that script (both components should be in the scene - don't reference the prefab unless you're just wanting to spawn the bird) you would be able to modify it's velocity via Rigidbody2D - it must have a Rigidbody2D to be referenced properly (the Inspector will not allow you to reference an object without that component and through code will just have you reference null if the object does not have said component).
my solution that i tried did not work. i dont mean to be rude by interupting _V's help
In unity, it would be the base class for all Unity objects and we'd use Instantiate to create new instances. In C#, an object would be the ultimate base class for dot net classes https://learn.microsoft.com/en-us/dotnet/api/system.object?view=net-8.0
Show your updated code - there is no line (anyone can ask anything at any time).
You might want to ensure that your IDE is properly configured if it isn't yet.
oh ok
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
do i delete the reds
You'd just remove the bullet hole graphics variable/field on line 27.
like this?
I chose to reference that same object as a Particle System to reduce unnecessary GetComponent calls.
oh ok
General rule of thumb is that you shouldn't ever have to reference a particular object as GameObject unless you're really not needing it for anything other than what GameObject can do - you can always access the GameObject using a component's gameObject property.
uh something happend
You see the first error?
The code was updated a few minutes after posting. #archived-code-general message
[SerializeField] attribute would show private fields in the inspector - private prevents other classes from easily tampering with them.
so do i reimport these?
You'd make it public if you're wanting other classes to modify the field - relative to explicitness.
tbh bro i dont know how to code
The above would make it show up in the inspector.
Reminder that you've got a type mis-match in the inspector as well - drag and drop the wanted object into the field.
What isn't showing? The Particle System?
maybe idk the effect from the prefab isnt there. its like invisable
Did you add the serialized field attribute?
yes
Did you save?
yes
Are all errors fixed?
yes
Show the current code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
whats happening
Booting up my Unity and verifying if Particle System is visible to the inspector.
oh ok for some reason my messages wernt allowed for a second
i sent an image of my code and it was red
the whole message was
Likely bot spam protection (too many messages or the messages were too small)
oh ok
It should be visible cs public class WhoAmI : MonoBehaviour { [SerializeField] ParticleSystem ps; }
You don't. Your inspector should be showing a field for your bulletHoleGraphic to be assigned in the Unity Editor Inspector.
theres no field for that
Maybe you've got console errors.
The component will not be updated if you've got errors.
Clear the errors.
Did you save the script?
Make sure you've assigned that and muzzle flash
its still happening when i click while reloading
i did for the muzzle and its still not showing
What's happening while reloading?
i can still shoot when the reloading animation is palying
the ammo counter goes down aswell
That would be a new/different problem.
Are there any errors?
So do the particles stop and start again when reloading?
Something to be concerned about
no way bro. i thought that meant how long it took the animation to play
it works
i feel so dumb
bzzt
the muzzleflash still wont show
you got that rendering on the gun camera?
yes the pixel art
or are you using 1 camera
two cameras, one for the gun to not clip through stuff and one for the pixel art and main surroundings
oh ok
wait so i put the muzzle flash effect as the same layer as the weapon? cause the weapon camera is just this
It's up to preference to how secondary rendering like post processing should affect it. More advance stuff such as changing rendering ordering is also useful for stuff like that.
oh because the muzzleflash is still not showing
Oh, you're just rendering a texture here, ah
kinda
But the particle system should still render if you don't cull the layer
do i put it on the same layer as the gun or the same layer as the enviroment
currently you've got it set to weapon
yes
you need to include the particle system layer onto it too
oh
so i have to write a new code for the weaponcamera to have the muzzleflash particle?
No, stick the particle system on the same gameobject as the weapon, or if it's on its own gameobject then the layer needs to be not culled by the camera
So, make a layer called something like MuzzleFlash and add it to the culling mask
on the gun? mb that i dont know anything
The particle system gameobject
im not sure how you're instantiating it so it depends how you are
ok so i applied the new muzzle flash layer on the muzzleflash prefab
ok
gtg in a sec, but ask more in #💻┃unity-talk if you have troubles
ok
would anyone know of a way to use Resources.Load<Sprite>() to grab an individual sprite out of a spritesheet?
im trying to use the name of the individual sprite in the sheet thats sliced but it wont load it
iirc, You have to use Resource.LoadAll then filter with .name
If you are using addressable assets they get subasset name and you can access directly
Other way is getting SpriteAtlas then using GetSprite
Hey, what is different about the player you want to get and another players? You'll have to know that to get its reference, because if they are similar, it should not be important whether to get one or another.
There are different methods, shown by the [answer below](#archived-code-general message), so you would usually use a Find method to find it by its Component or tag.
Find is the least preferred way. That page has other suggestions
I would probably store the main player in a singleton when instantiating it
Hi - i'm trying to rotate rigidbodies smoothly. I've been using rigidbody.moveRotation but it snaps to the rotation in one fixed time step. I need to be able to rotate from current rotation to a new set rotation gradually. What's the easiest way to do this?
If Rigidbody interpolation is enabled on the Rigidbody, calling Rigidbody.MoveRotation will resulting in a smooth transition between the two rotations in any intermediate frames rendered. This should be used if you want to continuously rotate a rigidbody in each FixedUpdate.
Go over the docs one more time, otherwise post code
I followed the documentation exactly. How do I post code? Just paste it?
rotMovementDirection = new Vector3(speedAdjXVelocity, 0, speedAdjZVelocity);
if (rotMovementDirection != Vector3.zero) newTransformRotation = Quaternion.LookRotation(rotMovementDirection, Vector3.up);
rotationVelocity = new Vector3(0, 10, 0);
deltaRotation = Quaternion.Euler(rotationVelocity * Time.fixedDeltaTime);
rigidbody.MoveRotation(newTransformRotation * deltaRotation);
this just snaps it in one fixed time step to the "newTransformRotation". I need it to move gradually to the newTransformRotation
the interpolation is set on the rigidbody in the inspector, try checking that
yeah interpolation is on
I had it working by setting transform.rotation but it messes up the physics if I use transform.rotation so I need to use a rigidbody function but be able to move from my current known quaternion to a new known quaternion gradually (i.e. not snapping the movement in one fixed time step)
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this methods being called in OnInspectorGUI but it's causing a great deal of lag the more notes there are. any ideas for how I would optimize it
{
if (notes.arraySize > 0)
{
for (int i = 0; i < notes.arraySize; i++)
{
SerializedProperty subProp = notes.GetArrayElementAtIndex(i).FindPropertyRelative("subdivision");
SerializedProperty posProp = notes.GetArrayElementAtIndex(i).FindPropertyRelative("subdivisionPosition");
if (subProp.enumValueIndex == subPos.x && posProp.intValue == subPos.y)
{
return true;
}
}
}
return false;
}```
Shouldnt it be MoveRotation(rotationChange * currentRotation) or something
Where does the (0, 10, 0) come from?
is it possible to cache these serializedproperties somehow
@somber vortex probably easiest to store your angles in floats and interpolate those (Mathf.MoveTowardsAngle). Then make a quaternion out of those floats (Quaternion.Euler).
well, you're getting back the serialized values each update. You can possibly limit to how much you're refreshing the UI with these new serialized values
so FindPropertyRelative is definitely the most expensive thing there right
been trying to narrow it down as much as i can
Btw, MoveRotation sets the rotation to the given value. It does not interpolate towards it or anything
not much exp with custom editor
#↕️┃editor-extensions probably the better place as it's not really common to find answers on the coding channels for it
good point
only thing I can think of those is just don't update the values if the object your are modifying isn't the active element
probably some ways to gauge it
no clue why those calls would fps drop you though as you're just doing a single index lookup
with a define path /shrug
the weird thing is it almost feels like a memory leak. it gets slower and slower as i move my mouse around
which makes me think the serializedproperties arent being disposed, so i tried disposing them manually, but no luck
thanks guys will try these suggestions
void Update()
{
if (isMoving)
{
moveCounter += Time.deltaTime;
float t = moveCounter / moveDuration;
t = Mathf.Clamp01(t);
t = 1f - (1f - t) * (1f - t);
this.gameObject.transform.position = Vector2.Lerp(moveStartPos, moveEndPos, t);
if (t >= 1f)
{
isMoving = false;
}
}
}
public void CloseGame()
{
Application.Quit();
}
public void MoveIn()
{
if (!isMoving)
{
moveStartPos = this.gameObject.transform.position;
moveEndPos = moveStartPos;
moveEndPos.x = moveStartPos.x - 2000f;
moveCounter = 0f;
isMoving = true;
}
}
```Im firing the MoveIn() by using it as a button .onClick() event listener, i want to make a gameObject's X position move 2000 to the side but whenever i fire the MoveIn method the gameobject X position goes to -216000
Any idea why its not lerping it to 2000 but to -216000 instead?
Btw moveDuration is a float with a value of 2
just checking this script is on the gameobject u wanna move right
Yeah
Also the gameObject has a rectTransform instead of a normal one
Im not sure if this has anything to do with it
OH yeah recttransforms are weird im pretty sure
one sec
lemme find where i did this
try localPosition
instead of position
this is what i did in my thing whereim moving recttransforms
element.localPosition = Vector3.Lerp(element.localPosition, toTarget.localPosition, t);
Yuppp that worked
Thanks man ive been stuck on this for a while xD
RectTransforms surely are weird
indeed
Hey ! In fact there no difference, just one is the player who we control and other player is other guys connected to same server .
I need to know which gameobject is the player we're playing/controlling
This is a #archived-networking question. Unity's forum suggests this line.
NetworkManager.Singleton.ConnectedClients
[NetworkManager.Singleton.LocalClientId].PlayerObject;
Oh okay ! i wasn't sure about if it was network or simple code ^^ Thanks !
Surely, it's network
As this has something to do with the other players
can someone help me please with my code (regarding rotation), i just can't get it working i feel so useless ._.
yeah ask it and someone may be able to help
i prefer dms than spam this here for the 9148928 time
that makes sense. you should describe the problem then prompt ppl to go to ur dms
cuz someone might say theyre down to help but be unfamiliar with the topic
You can make a thread
just trying to make a turret that's on the sides/top/bottom of a spaceship, which i want to rotate with the ship ofc, but rotate towards the target to shoot it (turret has 2 parts, one rotating only on y and one only on x) but i can't get it to work even tho it's simple i guess
Convert the world space position of the target into the coordinate space of the the turret mount.
Then project that local space position onto the desired plane
Then rotate the turret towards the projected position
public void SetCharacters(string Char)
{
Debug.Log(Char)
}
```Is this the right way to use the Button component OnClick event listeners?
For some reason it doesnt print out the string fencer
yeah but
i can't get it to work properly
Does it play the sound?
Yeah
Seems correct...
You sure there's no errors anywhere?
And you sure that's the correct script?
And you sure you saved your code?
Ill share the correct script to see if it helps explain the issue
But its basically what i posted
Can you show a screenshot of your console window?
After clicking the button
The full window
Mhmm pretty common
public void SetCharacters(string Char)
{
GameObject clickedButton = gameObject;
GameObject equippedImage = clickedButton.transform.GetChild(0).gameObject.transform.GetChild(0).gameObject;
if (UnitsSelected.Contains(Char))
{
equippedImage.SetActive(false);
UnitsSelected.Remove(Char);
}
else if (UnitsSelected.Count < maxUnits)
{
foreach (string i in UnitsSelected)
{
Console.WriteLine(i);
}
equippedImage.SetActive(true);
UnitsSelected.Add(Char);
}
}
The Console.WriteLine(i); isnt printing anything
Oh this is very different code
Why are you using console.writeline in unity
Debog.Log is what you want
Answer from where lol
Someone who doesn't know Unity
Anyway there's like 3 conditions that need to be true for that code to run
So It's very possible it's not running
It's nothing like what you posted TBH
Ive been debbuging most of the code
And the only issue i could find was that the parameter wasnt passing anything
well if this isnt outputting for them, its possible it's not the code
With Console.WriteLine?
No i was only using console log for the list
Yeah why lmao
You need to add more logs
Check all these conditions
Check the length of the list
Etc
Debug.Log only, no Console
Yeah, you don't really use System's Console unless you're writing a console application or using a framework that uses the Windows console or Linux terminal.
Yeah seems like the parameters are passing fine
Im trying to deactivate/activate an image with that code
But the image doesnt change at all so im guessing equippedImage reference is the wrong stuff
can u explain what this is supposed to do
im having trouble understanding the conditional
Its a character selection screen
When the player picks the difficulty, it sets a maximum amount of characters it can select(maxUnits)
And when it selects a character, its supposed to add it to the list of selected characters only if theres enough space
Theres also an image that activates and deactivates to make it clear if the character is selected or not
But the image doesnt change
I think it may be the way i reference the image
could try
GameObject equippedImage = clickedButton.transform.GetComponentInChildren<Image>().gameObject maybe
its hard to look at new code and understand it, but is weapons not being cleared when u unselect the weapons
it clears on Awake
Nope, basically the same result
I just tried debugging and it seems like its referencing gameObject to the gameObject of the script instead of the button gameObject
GameObject clickedButton = gameObject;
its setting it to the object this script is on
ChatGPT recommended this for me some time ago
ya its assuming the script's on thebutton
Ohhhhhh
gameObject will always return THIS object
thats why u dont need to write "this.gameObject"
{
notebook = GameObject.FindGameObjectWithTag("Notebook").GetComponent<Notebook>();
GetComponent<Button>().onClick.AddListener(() => notebook.SelectClue(GetComponent<CombineNotes>()));
}``` I have this piece of code of a piece of text that is instantiated during playtine and I need to give its button an event. For some reason it never does this though and it has everything necessary there. Does time.timescale make a difference
No it doesn't
just tested it
it has everything connected but just can't make the button
so i tried to do this
Vector3 direction = target.position - turretBase.position;
Vector3 localDirection = turretBase.InverseTransformDirection(direction);
localDirection.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(localDirection);
turretBase.localRotation = Quaternion.RotateTowards(turretBase.localRotation, targetRotation, horizontalRotationSpeed * Time.deltaTime);
i don't understand InverseTransformDirection, because if i rotate the turret it looks in the right direction but not at the target
turretBase shouldn't be rotating
what
There should be two objects
The base
And the turret itself
The turret should be a child of the base
the base is the part that rotates horizontally and the barrel i add later vertical
You need a third object then
A base, the horizontal rotating part, and the vertical rotating part
Ok then the turret itself needs to be what you're calling inverse transform point on
what
That's what I meant by the mount here
the parent is the object the script is on
so"transform.rotation"
what am i supposed to change now
i am trying to make this shit work for so long now pls just end my suffering
Are you trying to rotate a turret towards the player?
towards enemy spaceships yes
but i want it to rotate with the spaceship the turret is on
and still rotate towards the enemy
(also, only on one axis)
The angle can be gotten by getting the tangent of the ordinate divided by abscissa
ah here we go again my brain is already melting
i don't know what that means
Have you gone to school?
yes 
Have a look at this
That's the formula you need
no
Also I meant the reversed tangent
Then don't
I have provided the formula for you, and now you start whining for... not writing the full code for you?
Perhaps, I also should send you a full .unitypackage file with the solved issue?
Get down off your high horse megamind
i am so sorry my adhd brain can't learn that shit and i know from experience i shouldn't even try. and it not being in my main language makes it even harder.
i am not dumb, i already have a game with multiplayer and mod support and i just asked what i have to change in my code to fix it. and a formula doesn't help me personally ._.
{
public abstract void StartSkill(Unit user, List<Unit> targets);
public abstract void FinishUse(Unit user, List<Unit> targets);
public abstract void TriggerChannel(Unit user, List<Unit> targets);
public abstract void End(Unit user, List<Unit> targets);
public abstract string GetSkillDescription(Unit user);
public SkillData Data;
}```
i have this abstract SO Skill class with a SkillData class with basic stuff like skill name, cooldown, cost, etc
inheriting and overriding the base functions lets me have good control of how a skill functions
my problem with this is each Skill is just referencing the SO, if i wanted to change something in SkillData like the cooldown, it would change the base SO
what's a way i can tackle this?
arent scriptableobjects kinda like abstract classes themselves
wouldnt u just make instances of a Skill
you mean with ScriptableObject.CreateInstance()?
They're expected to be immutable data (components) that are not associated with Game Objects.
nah like make them in the project window
unless u need to make them at runtime
i do make them like that and it works well until i want to modify its properties at runtime
You can just copy data from the SO and modify it as needed on whatever class stores it. Instead of directly just using the SOs values, which yea you shouldnt change
copy the data how? ScriptableObject.CreateInstance()?
i would say try removing abstract? i dont see why u need them unless im not understanding something
couldnt it just be a scriptableobject
No, by just storing the relevant fields needed
Please dont guess answers, this clearly has nothing to do with the actual issue presented
i have other skills that derive from the base Skill, each with its own unique code and values
ohhh gotcha
could you give an example?
not entirely sure what you mean
All the relevant data you need is probably in SkillData, literally just copy that field from the scriptable object to whatever class uses the SO.
Im not sure what else to say to explain it, it's just
SkillData myData;
And you copy it from the SO
that sounds doable yes, the problem is i would lose some flexibility with having each Skill have unique values that aren't in SkillData
You don't have access to those values anyways if all you ever reference is this Skill class
skill.Data = new(skill.Data); constructor to copy the data
skill.Data.cooldown.BaseValue = 1; changing value of data
seems to still modify the SO
If cooldown or BaseValue are classes
they are references
so your copy is referring to the same instance of them
depending on how your constructor works
oh big true
{
...
this.stats = new(skillData.stats);
}```
still the same issue 🤔
do i need a Stat constructor that copies a Stat?
what is skillData.stats
what does new () do on the constructor for it?
skillData.stats is a list of the Stat class, new there just does the default constructor for lists
oh wait
you mean the SkillData constructor
List of WHAT
{
...
this.stats = new(skillData.stats);
}```
oh is stats a list
yeah
ok so yeah I mean
what is Stat
if you're just making a new list referring to the same Stat objects
then you still have a problem
you'll want to create a new copy of each stat
Assuming Stat is a class
yea big true ty working on that now
Is there any reason of Stat being a class, not a struct?
never thought about it really, haven't used structs much, it's just value vs reference right? i do need to reference stats a bunch, would i still be able to do that with it as a struct?
You wouldn't be able to reference one and have it affect the original in the list
it depends if you need that ability or not
Using structs would save you from having to write copy constructors etc though
and has the potential to be more efficient.
So it really depends on what you're doing
i do need to reference them unless there's other ways to make changes to them that doesn't involve references
The other way would be knowing where it is in the list and overwriting it.
in effect a "pseudo-reference" consisting of a reference to the list and the index in the list.
i could possibly do that
{
baseValue = _stat.baseValue;
...
}
public SkillData(SkillData skillData)
{
this.stats = new(skillData.stats);
...
}```
this is still modifying the SO
yeah you need to acrtually call that
so like:
foreach (var oldStat in oldList) newList.Add(new Stat(oldStat));```
gotcha
One question though
baseValue = _stat.baseValue;
is baseValue float?
Or some class?
double
ok that's fine then
as long as none of the fields inside Stat are classes then you're good
Could be either one, but if it's in the class itself you get access to private variables
Usually it'd be in the class itself
right right
will new use the list constructor automatically or do i have to call it somehow?
It's a target-typed new
It'll call a constructor for the type on the left hand side of the assignment, in this case
so yes, it'll construct a list here
this may be a monumentally stupid question but is it possible to make strings editable like TMPro data
Like with the big edit box