#archived-code-general
1 messages ยท Page 67 of 1
I mean, yuo can probably with reflection and editor tools, but thats not gonna work on runtime
and you want that enum to reflect the states in your animator?
You should make a transition then and check the next state
Why do you even use the animator then?
just use the animations you throw into it
It all depends on your animations tho
but your animations are clips inside your animator
every state holds an animation, right?
If you do not use the animator for anything transition like from one state to the other, you can just use the Animation itself, the AnimationClip
Or you just create an ANimationState on the fly and throw in the clip as state clip
just add an ANimation Component to your object instead and add your clips to the list
Hello, not too sure if this is the right place to ask this but, Im new to Unity's AR foundation, and I am trying to add an image as a background so that it shows behind the users face, Im trying to use the Custom material in the AR Camera Background but ll im getting is a black screen when I enable it. If anyone can help with that would be much appreciated.
#๐คฏโaugmented-reality is your place ๐
Oh thank you , I dunno how I missed that channel ๐คฆ
Is it possible to modify this template so that it accepts interfaces too?
Or the interfaces so it's known that they are inherited by ScriptableObjects?
public abstract class LootTableBase<T> : ScriptableObject where T : Object {
I was ๐
What exactly are you trying here? Pass in a generic type?
Interface != class
So there's no way around this you think?
I do not even know what you want exactly ๐ can you elaborate in more detail?
I'm trying to intergrate this into my code, but I'm using Interfaces on ScriptableObjects for my different type of loots
While this thing from Github expects ScriptableObjects
Wdym by this and what does it have to do with your generic type
to use an interface.
So you can use that interface of type ILootable or what not to do what you want
I'm not quite sure what the question is, let me add a bit of information. I am already using interfaces on my scriptable objects, is called Lootable, but if I try to use it as is then I get the following:
you have a type constraint on your generic
that it must derive from Object
(UnityEngine.Object)
Yeah, but could this be changed to not have that?
sure, delete the type constraint
remove where T:Object
Alright, I'll import the whole code base then and try to modify it, thanks!
public class Test<T> : ScriptableObject, IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}
public class SubTest : Test<IEnumerable>
{
}
Didn't want to get into it if it wasn't doable, it might break somewhere else but atleast it's a thing
Is there a way to get Application.isMobilePlatform to return true; or Application.platform == RuntimePlatform.Android when running the game in simulator mode?
I have simulator setup to use Samsung Galaxy device, but both of these return false.
What would I replace T : Object with though?
Not sure I get what you mean here
Okay yeah I can just remove it haha
Just had to remove it in many places
nothing
Does unity have built in multiplayer modules?
I havent dared to mess with multiplayer yet
Unity has lots of packages for lots of things
depends what kind of "multiplayer modules" you mean
Like, a basic way for 2 people to connect to the same server
Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport.
Thank you
There's nothing "basic" about networking or multiplayer in general
Yeah thats why I havent messed with it lmao
What does this line indicate?
I am accessing the unity classes in the vs anyways. I dont think theres any better experience than having a configured ide
As the warning says, go to settings and set vs as the external code editor. It'll give you better syntax highlighting, intellisense and autocompletions
Alright, after having googled and thought about it for a long time, its now time to ask the awesome folks of discord for an answer to my question.
Im procedurally generating a mesh in my scene to act as a debug overlay in development.
The overlay is showing all the "tiles" of the map. This works great for one color.
But now my question becomes, can i have more than one color on one mesh?
And i dont mean two colors that blend, i mean two colors at two different spots in the mesh.
Do i have to somehow procedurally generate a texture and apply it?
already did that earlier though
ahh maybe needs a restart
Why are you on ancient unity
I'm one of them, Ancients
Probably has to do with the 6 year old version
yep ๐
Restart did nothing *presses the Do Not Warn Again and continues life*
Is there a reason you use that version of unity?
Cause I highly recomend updating if there's no reason
You could use vertex colors instead of doing uvs and a procedural texture
This is the only version that can run for my 2013 laptop
Fair enough
We can CTRL+Scroll on vs ๐ฏ I might actually love vs
Yes, you need to duplicated your vertices so the colour does not blend. If you want colour in specific spot that are inside a triangle (does not correspond to a whole triangle), then you need to use UVs.
So effectively making two different meshes?
No, just making sure your triangle does not share any vertices.
how do i then assign a specific material to the triangle?
Use vertex colour.
and youre right btw, i dont need different colors inside of a triangle, single colours are good enough
ill check it out ty.
I am only now understanding that you meant the same as Simferoce :>
hm, one question, this seems to use the Color class rather than a Material class. Am i correct?
hey dude sorry for such a late reply i was in school the code you gave completely demolishes the procedural generation
this is the map it creates
Colour vertex use none of them. It uses Mesh.colors. (https://docs.unity3d.com/ScriptReference/Mesh-colors.html) You then need to find or create a shader that use color vertex.
its okay and hmm I understand it has to do with the "checkCellNeighbour" function since that one needs all of them to be generated
hi, when I import models from Sketchup, my character can walk right through them, meaning they are not solid objects, how to fix?
Add a MeshCollider or other type of collider on the object.
basically, ths part that uses the checkNeighbourCells needs to be in a seperate loop, after the generation. but also, if you really want speed you could also try writtinf a compute shader, those like to be fast. im tired atm so ima go sleep noa
ill look into it when i waje up
gave a good sleep dude, and i will look into compute shader
tysm
Hey, so for a few hours I've been trying to refactor this code so it can accept Interfaces too, my issues is that, even though my interface is of a ScriptableObject, which would work with the rest of the code, I'm unable to properly figure out what to do.
What I've done so far is refactor T : Object for T : INameable which has a GetName() method, but it becomes an issue because a lot of the code is based on Editor Serialized property so I get a lot of errors even though it builds..
The interfaces are always of ScriptableObjects but I'm not quite sure how to make that clear in the code, if it's possible.
Any ideas why the font I downloaded displays as white squares? I tested it online and it is fine, but in unity with text mesh pro it just doesn't work
Hello, voice chat is quieter in some places, but in the centre of the map, it is really loud? How do I fix this? I use Photon VR Voice
probably related to where you put your audio source
Maybe you are looking for https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint. But beware, I am not sure the inspector handle well generic type. In fact, it might not even be serialise correctly.
Mhm, that's what happen'd.. I was hoping there was a way but I think at this point I'll just use ScriptableObjects..
they are in the middle of the map
ok so problem solved
players spawn in the house in the sky
that's why it's quieter farther away from it
how do i get it to follow players
make it a child of the player
You can use SerializeReference also. It might work for your use case.
@steady moat mesh.colors worked wonders, helped me squash my pathfinding bug in no time, thanks!
do you reckon this affects it too?
How hard would it be to programmatically quiet everything but the announcer group here when something from that group plays?
Pretty easily, you would just need to set the volume to everything at -80 for the given time the announcer is talking. Even better would be to make an other node that regroup everything except the announcer.
Note that the AudioMixer as a non intuitive API and you may want to read on how to change the volume in script.
Okay, thank you. I'll let you know if I have more questions
i have an object wich is a child of another object sometimes and i need to make it os the chil is always rotated upright. I tried it like this but it gave me very buggy results. what could i change ?
How can I use NavMesh.SamplePosition in a two story building?
The method is sampling from the wrong floor.
Is there any workaround?
Do scriptable objects reset their data when the game is quit and reopened?
Interesting. Thank you
Hm, this is changing the color correctly, but it isn't changing the alpha
(the debug is showing the correct alpha number though)
Relative to naming conventions, you would be changing the color of the prefab.
Maybe you're wanting to change the color of the instance instead?
No it was just bad naming. Should be instance
the color does change, just not the alpha for some reason
It's just the sprite unlit default material
calm down, it's been 2 minutes and you already crossposted it in 3 channels
post it in one channel and just wait
ok
I am having some trouble with lerping my game volume. I am setting the values in Wwise and my mixer group, but although both of them appear to have updated when I debug them, they don't actually change in game.
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.
Here is my log
As you can see the values when I get them directly from where I set them are updating correctly, but they are not actually changing at all when I play the game. I am testing this by calling it in Start. Does that not work? Or is there another problem?
this is probably supposed to be in a coroutine. otherwise the while loop runs to completion immediately (in a single frame)
How can I access one of two box colliders on a game object with GetComponent<>()? (one is a trigger, the other is for physics)
That is not a Lerp, that is a go from A to B the difficult way
Don't use GetComponent. Use a direct serialized reference (drag and drop)
what's that
and how that
It's unity 101
one of the first things you learn
declaring public variables and assigning them in the inspector
How would you suggest it then
I don't think I can do that, this is my code
public void Place(GameObject part)
{
partBeingPlaced = Object.Instantiate(part, new Vector3(), new Quaternion());
// select one of the two box colliders of the game object "partBeingPlaced"
}
You can absolutely do that
put a script on your prefab, and add public fields to it. Assign those fields in the inspector
That would make sense
new Quaternion() is not a valid rotation btw - use Quaternion.identity
and Vector3.zero
Because I'm pretty sure this does work, just not in start or awake which is kind of a weird bug
But based on how pumpkin described it, it makes sense
idk what's going on there, it requires a Quaternion and it sets it to zero, no errors, so I'm ok with that
It's because I had opacity set to 50 when alpha is actually supposed to be between 0 and 1
Quaternion.identity is the correct way
you probably get a warning with your current way.
I don't
Trying to teach you better practices, that's all. You don't have to accept them.
Is there some dumb reason that I'm missing as to why I cannot add new tags?
Can someone give me a hand? I'm trying to assign randomly a total of 26 tags to Instantiated gameObjects, but its assigning the first tag only, going over the limit.```cs
public GameObject floors;
private int MaxFloors = 26;
public Material Enemy;
public Material Weapon;
public Material Empty;
string[] tags =
{
"Monster", "Empty", "Weapon"
};
int[] tagCounter = { 14, 5, 7 };
int index = 0;
void Start()
{
for(var i = 0; i < MaxFloors; i++)
{
GameObject newFloor = Instantiate(floors, new Vector3(i * 20.0f,0,0), Quaternion.identity);
for(int j = 0; j < tagCounter[index]; j++)
{
newFloor.tag = tags[index];
index++;
if(index >= tags.Length)
{
index = 0;
}
}
}
}
You don't need or want the inner for loop
delete the inner for loop
Any imported fonts in current project have 0 characters and glyphs when converted to tmpro asset. Now on another project, they are working fine. Any ideas?
its not tagging now
If you need more context, I need 14 of Monster tag, 5 of empty and 7 for weapon
Then you would need a second variable to track where you are in the tagCounter list
i instantiate an object, i place an object with a collider for its child, i begin creating more objects as its child, i try to raycast from outside inward to see where it hits and try to place the child there, but it wont intercept a single collider despite it clearly intercepting colliders
im probably just not seeing something very simple that im overlooking
but ive debugged the ray, i can see it intercepting the collider, i checked that theres a collider on those objects, i dont believe the Z axis is interfering with the operation, i really dont understand the issue
i printed how many RaycastHit objects its returning and its telling me 0
so its just not hitting anything
but i can see the debugged rays hitting the objects, and honestly im just confused
my only real guess is that they might have inversed direction?!?
but wait.. that cant be because the origin value is set as the origin of the ray, i wouldve clearly seen if the direction was inversed because it would go the opposite direction from the origin value facing away from the object
im confused :/
The physics scene doesn't update until the next physics simulation step.
But you can force it to update with https://docs.unity3d.com/ScriptReference/Physics2D.SyncTransforms.html
So if you're placing colliders etc you won't see them with raycasts until either the next physics sim or you call that^
oh.. alright thanks
so every time i instantiate an object i have to sync transforms?
or do i do it after i position the object?
since it has to do with transforms
ill do it after positioning just to be safe
hey it works! thanks a ton, wouldve never guessed that
I'd say do it right before you do a physics query
alright
Back on this, they were right. How should I lerp this?
There was a dumb reason. The tag already existed.
How do developers approach programming their games? I'm aware that the potential answer will be "It depends on the project," but I'm more so referring to the common things people do when developing code for their project. How much online research do you find yourself doing to code something specific vs figuring it out on your own?
I've had experience programming outside of Unity and I tried to figure out how to answer programming questions from classes on my own save for very specific questions i wanted to find the answer to on stackoverflow. But those questions were pretty simple while doing a unity project is a lot more involved. A common thing I see online is that most of programming is looking up what your asking to code and then basically copy the answer to your own code base, but I'm worried that's going to develop bad habits.
If the question is confusing and need to specify anything please let me know.
I try to figure out a solution by myself, but will afterwards look for others' implementation if my code is too slow. Don't look too much for a single solution. I have found it to be better to ask for pointers. These pointers will introduce me to new concepts that I can then look up and experiment with. Examples could be dictionaries, Unity events, or singletons. All of these things I wouldn't know existed without asking people for help / looking up other people's code.
This is just my own experience, keep that in mind
Also, showing your code to other people and them telling you: "You suck! X is a much better way to do it", is what I learn the most from
lol glad you took it in stride. Thanks for the advice!
How can I switch the noise profile of a cinemachine virtual camera from handheld to 6D shake from code?
"A common thing I see online is that most of programming is looking up what your asking to code and then basically copy the answer to your own code base, but I'm worried that's going to develop bad habits." Agree, this is awful, at least if one is copy/pasting the exact code- one learns nothing, and introduces possible problems. Of course, there is nothing wrong with finding/learning an efficient way to do something, and applying that pattern in your code. The one exception to using others' code- well vetted libraries/packages: you don't want to spend time re-inventing the wheel when you can use a perfectly good one.
what could be a better practise than showing a visual guide of a specific task after getting a hearing guide on how to do it?
not sure using an IEnumerator is such a good practise, but im not sure it isnt either
โ๏ธ that
how do I set the TextField size to a number, and it's label to fit?
editor TextFields
https://docs.unity3d.com/ScriptReference/Assertions.Comparers.FloatComparer.html What does the "absolute error check" mean vs "relative error check"?
Thank you
That makes sense
Where do you find the code? Do you look through the github, or is there a link in the docs?
I search their github org
@rustic ember This may be interesting
https://scicomp.stackexchange.com/questions/3362/relative-comparison-of-floating-point-numbers
absolute (abs(a-b) < eps) as well as relative (abs(a-b)/max(abs(a), abs(b)) < eps)
Not really what I was looking for, but certainly interesting. Thank you
Hey, I wanted to ask how I can detect collisions while an animation. Thanks for any help
wouldn't you just use normal collision detection techniques?
On collision enter does not work for objects moved by an animation. Suposably because it overites the reansform instead of using physics. But i am not sure about that one.
OnCollisionEnter only is going to work for dynamic Rigidbodies period
animation or no
obviously if you're using an animation to move it, it's not dynamic
What would be a smart way to let the player select a character before going into a level/changing scene and let the GameManager in the level scene know which ones (characters) were chosen?
keep a GameState or GameData object around on a DDOL object which contains all information about the current state of the game
including chosen characters, equipment, etc...
How do I change that then?
you wouldn't change that
you just can't use OnCollisionEnter
Thank you. I totally forgot that DDOL was a thing
What can I use instead?
Can a DDOL object have a singleton script attached?
sure, why not? in fact making a singleton DDOL is a common pattern
OnTriggerEnter
Direct physics queries (Raycast, OverlapBox etc...)
So i've almost got my player to slide down steep slopes
However the way the player slides down is a bit bumpy
{
var normal = player.hitNormal;
player.velocity += new Vector3(normal.x, -normal.y, normal.z) * 2;
}```
mainly on really steep slopes
Wait does RaycastAll return hits ordered farthest first???
https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html
Note that the order of the results is undefined
What why unity!๐ญ
Probably because of physics engine optimizations
You can still order in your own code though
I know that I could just rename the script, but is there a way to override the built-in and avoid the warning?
yes, change the namespace in your script
Yeah just gonna write a static extension that orders them, just weird that it wouldn't be ordered but I am not familiar with how physics engines work so \(-.-)/
How? What do you mean?
do you not know what a namespace is?
Yes. but wdym "change the namespace in my script"?
You mean not use UnityEngine?
I still need the MonoBehaviour part
if you have 2 CharacterControler scripts, you can seperate them by making one of them MyNameSpace.CharacterController, thus removing the warning
public class CharacterController : UnityEngine.MonoBehaviour
Oh smart. I didn't know
This seemed to work as well
But will kind of suck in the future
only becaue you have spelt it incorrectly
Controler does not have a double l
You're joking right?
It does have two l's
sorry, my bad
Yes
Though Unity controls the project file, so they are linked
it actually depends on the unity versions. for example 2021, 2022, and 2023 are all on c# 9
Can't bump the C# version alone, as Unity will override it when the project file is regenerated
Ah, ok. I figured something like this was the case. How can I see which language versions the different editor versions use?
It's listed online
Thanks. Why are there two?
because it depends on the scripting runtime version selected in your project settings like the text directly above that table says
Right, sorry. How can I see which is the default?
you can check the setting in your project to see which it is currently on. if you've never changed it then you know that is the default
but also is there a reason you are using 2018 and not a more modern version?
I am using 2020 for my new projects
the table you linked is from the 2018 page ๐ค
Hey,
what is the right way to Convert string to int ?
int.TryParse
Should only be done if you're handling user input basically
it did work , thanks โค๏ธ
so uh advanced seems pretty dead right now so i guess ill ask here
No, that's crossposting.
Regardless, it wasn't even an advanced level question. It's beginner at best. You look up how to do AI. That's where you start.
so i should remove it and post in beginner?
because ive looked it up and i dont understand a thing
You don't need to post, the answer is: figure out the rules for your AI and implement it. Research as well.
There's no one way.
i have so many "rules" that im just sorta puzzled, i guess ill try my best
my issue is that i dont really know where to look, theres so many resources on AI but they all talk about specific algorithms that all have very different ways of "learning" so to speak, and i dont really know where to start
if you could atleast reccomend an article for where i could look it would be much appreciated
If the image is off center in the camera, is there a way to center it without moving the camera?
wdym "image"
like a ui element?
I'm not going to look online for you. You can start with State Machines with regards to AI.
ContactPoint contact = collision.GetContact(0);```
Why first line exst if on the doc they said to not use this method ?
GetContact was introduced as of 2018.3
Whats the best way to scale movement between two different ranges? If I have 1 m arm and I rotate it so it's level with the base and then I want to take that distance that I rotated and apply it to a 10m arm but scale it in a way so that the 10m arm moves to be level, how would I do that?
how you know
it's in the documentation
ok
ok
Assuming these are vectors, lerp rotation and magnitude, then combine
Or slerp
you can use camera perspective editor from the asset store if you want to easily do this
Hey! So I had something I've been trying to figure out for the past 2 days, I have prefab clones which are instantiated into my scene after the App has launched, part of these clones is a button that is supposed to disable a component of another gameobject that already exists in the scene from the start, but I'm not able to directly connect it through the inspector to the button click event due to it not existing in the scene, is there a straight forward method to assign it? Or would it have to run through a coded method in order to access that component?
I have a script that contain this line of code Application.targetFrameRate = 60;
and I have attached it to an empty game object and I also have like 5 different scenes on my game, do I have to attach this script to a game object in every scene ?
so i an using [ExecuteInEditMode] to place prefabs in my scene and give them a name related to their position.
for (int PosX = 0; PosX < Width; PosX++) {
for (int PosZ = 0; PosZ < Length; PosZ++) {
GameObject tempTile = PrefabUtility.InstantiatePrefab(tile, transform) as GameObject;
tempTile.transform.position = new Vector3(PosX, 0, PosZ);
tempTile.name = PosX + "-" + PosZ;
}
}
it get disabled afterwards so it doesnt run the next time i click play. however the next time i click play all the prefab's custom names get reverted to the original prefab name. how do i fix this?
they dont change their name anywhere else
very cool, thanks
You only need to do it once. I would recommend not using targetFrameRate, if possible. It's implementation is a bit shoddy and can cause issues in some specific cases.
Do you have any more information about that? I feel very uneasy leaving framerates uncapped by default (unless you recommend vSync instead or something?)
Would this be the right place to ask for recommendations on my singleton implementation?
Or would that go in Advanced?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManagerScript : MonoBehaviour
{
private static GameManagerScript instance;
private static int points = 0;
private static bool havePackage = false;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
}
public static void AddPoints(int p) { points += p; }
public static int GetPoints() { return points; }
public static void LoadGameOver()
{
points = 0;
SceneManager.LoadScene("GameOver");
}
public static bool CheckHavePackage()
{
return havePackage;
}
public static void SetHavePackage(bool hp)
{
havePackage = hp;
}
}
So, that's currently what I'm doing. I suppose all the other methods aren't important, but I honestly just don't understand singletons.
Seems like a just-fine minimal singleton implementation
it doesn't use DDOL so it won't persist between scenes but that's not always desired.
although
you should NOT make all your variables static
I just noticed that
Oh. I thought you had to.
the only thing in this whole script that should be static is this:
private static GameManagerScript instance;
everything else that is static should not be static
You should also make a public accessor for that field
Interesting. A video I watched about it said otherwise. Or maybe I just misunderstood.
public static GameManagerScript Instance => instance;```
you misunderstood
or it was a bad video
remove static from everything except instance, and make instance public
then you're good to go
Awesome. I'll do that. As for DDOL, where would I implement that if I wanted that feature?
In the awake method?
The idea of a static Instance is so you can call any public variable/function from the Instance directly, if you wanted to call data from the GameManagerScript class itself, then making other parts of the script static makes sense, though in this case it doesnt seem youd want that
in Awake, yes
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManagerScript : MonoBehaviour
{
public static GameManagerScript instance;
private int points = 0;
private bool havePackage = false;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
public static void AddPoints(int p) { instance.points += p; }
public static int GetPoints() { return instance.points; }
public void LoadGameOver()
{
points = 0;
SceneManager.LoadScene("GameOver");
}
public bool CheckHavePackage()
{
return havePackage;
}
public void SetHavePackage(bool hp)
{
havePackage = hp;
}
}
woops
forgot to remove a couple of static references
But this is what I have now.
DontDestroyOnLoad(gameObject); should only be in the if statement right after instance = this;
Do you have any more information about
Perfect. thanks!
So, okay, follow up question. Since I removed the static references, when I want to call one of the methods in my singleton, I'm have to say GameManagerScript.instance.[some method]();. Is that the expected way to reference methods from my singleton?
yes
kk
that's the typical way to use a singleton
thought so, but wanted to double check.
It's not generally good naming convention to use the word Script at the end of your class names
We already know it's a script
that isn't adding anything
in fact it's not a script. The type represents a GameManager instance itself
not the script.
I only do it cause I named a script "Camera" one time and it messed me up for days.
I'm just paranoid I'm going to name a script something that is already a reserved word and frustrate myself for days again.
Otherwise I agree. I don't like adding that word, but keeps me from using reserved words by accident.
Camera is not a reserved word, it's just the name of an existing class. If you get comfortable with the use of namespaces, it's not a problem at all. You can also just very easily see which type is being used in your IDE by hovering over it or cmd clicking it
that's a mistake you only really make once
(the mistake is not naming your script Camera, but not realizing what the issues was for so long)
I mean, yea, I think I'd recognize the issue a lot quicker next time at the very least. I'll have to try the cmd clicking thing you mentioned. Never done that before.
(ctrl if not on a Mac)
basically get familiar with your IDE
it's a tool to make your life easier
it has all kinds of features that let you jump around the code and understand the code you're looking at more easily
If it helps, I try to name my scripts based on what they do, just naming a script "Camera" on its own doesnt describe what it does, if it moves the camera based on input, maybe "CameraController" makes more sense, if it takes screenshots from the cameras position, maybe "CameraSnapshot" makes more sense, this way you know both what the script is intended to do by its name alone, and hopefully wont run into issues of confusing reserved names
Does this mean that you would also then use multiple scripts on the same game object depending on the functionality that the scripts offered?
I think that's why I've named my scripts the way I have - I have wanted all functionality for the player object to be contained in one script, which then contains all the functionality for the player object. So, naming them on the function they provide hasn't been very obvious for me (unless a script I've written only provided one function in the first place).
Typically I would, yes, I have a specific naming convention that helps me know the general intention of most scripts I write, which may come with time and developing your own naming convention that makes sense to you, but its actually easier when you get used to using multiple scripts instead of trying to have 1 script do everything - for example, if I wanted to make a playable character, I might have a "InputManager" to detect movement keys, and a "PlayerController" to hold functions for movement, maybe a "CharacterController" if I wanted to control the physics of movement, maybe a "AudioPlayer" if I wanted to have footsteps when you move, etc
This way if theres a problem with say input, I know which script its in and I dont have to scroll through a 2000+ line script to find 1 function, it also lets me reuse parts of a script for other systems - say I wanted to add AI, they move, I could reuse the "CharacterController" and "PlayerController" since the "player" only moves from input, while AI doesnt, but physcally moving is the same
I posted this in the network channel as well but I'm casting a large net :D. Whats the best approach to sync clients joining a session in progress? The issue I'm currently facing is all the network objects that have been destroyed are frozen in place at the place they were destroyed at before the client joined. I'm using a ClientRpc as well as a ServerRpc to return objects back to the pool. There's also some other weirdness happening on the client but I'll tackle that next. In the screenshot you can see frozen missles left over from the host(on the left) on the client(right).
If it wasn't for MonoBehaviour inheritance, GameManager would've be as easy as calling
public sealed class GameManager {
private static GameManager _instance;
public static GameManager => _instance ??= new GameManager();
private GameManager() {} // to avoid accidentally ctor elsewhere. Also - should not invoke any expensive ops.
}
Hey ,
why does the following sample fails sometimes ?
float _temp = default;
float.TryParse(textMeshPro.text, out _temp );
_temp = _temp + 0.1;
textMeshPro.text = _temp;
the function above is a response to a click of a button, the error I get ( not a console error but a visible one )
it works fine several times , the number is increasing 0.1 on each click , except that some times it increases 0.10000001 , whcih appears on the display instead of 6.2 > 6.20000000001
what is wrong with it ??
that's normal due to floating point precision..
is the format 0.00000000 necessary? if not you can just do ToString() with an overload to format it so you don't need to do roundings etc
textMeshPro.text = _temp.ToString(); ?
but with an overload to your floats
what do u mean ?
myFloat.ToString("0.00")
Gotcha. Also apologize for delay computer crapped out on me
Ohh ok , thanks , first time to learn abou the string formates ^^
Guys how can i calculate this spawn location. The black circle is the map size. The red circle is radius from the main player. I want to randomly spawn enemy in the green area where is it not out of bound of map area (black circle) but also not in the area of main player. The player will always be inside map area.
i have a way to brute force the solution where i just find a random location inside the black circle, can calculate the distance to the player. If the distance is smaller than the radius from player, find another random location.
this seems really slow and inefficient in the worst case that it might keep randoming inside the red circle.
is there better way to do this mathematically?
You'd have to write your own equation to deduce a value between 0 to 1 , which can be used to receive a random range value and receive a valid location coordinate from that call.
Anything wasted would be a wasted call.
Could consider SDF, or reclamp value to nearest?
instead of finding a point then caculate it, how about you give it condition first then find the point later?
im trying to calculate this. Find green area to spawn. But i havent found a way yet.
I tried asking chatGpt but seems like it does exactly like what you did
which is kinda inefficient

you could maybe do a similar approach but instead of trying new random points every time. Take the old "wrong" coordinate and shift it towards the black circle center. so in a sense you would use the initial random position as a seed and then trying to correct it. in some cases you might have to shift it away from the black circle center. So i would take the first random position, then try both moving towards the circle center and away from it. then try a different distance if that wasnt successful. the trick is figuring out the sweet spot of how far to move and where. But im 90% sure that in all cases theres a solution by either moving away or towards the black circle center.
hope that gives you an idea of something different to try
I reckon there's a lot of edge cases with this approach
E.g. generating a point directly on the red circles pivot, or to the far edge of the black circle, which the red circle overlaps
hmm there might be, where there would definitely be some is if you move towards/away from the red circle center. i have to be honest i cant visualize edge cases for moving away/towards black circle center, but ill take your word from it. I mean once you get the distance just right i think it would work. I think they might also be able to figure out a safe min/max distance for this method with some geometry. If they simply move away enough to be further from red circle than red circle radius they're in the green zone. either away or towards the center, or anywhere if red circle and black circle share a center. once again, I may be missing cases though
this is what i have in mind
bascailly the blue arrow representst he opposite direction from the player
thing is with this it may put the enemy out of the black circle. imagine spawning just northeast of the red spot, it would move the enemy out of both circles
if the enemy is pushed out of bounds, make it go in the same dir from the player to the new location
to prevent things like the enemy moving weirdly around the map, make an invis gameobject that calculates the location for the enemy and make the enemy go to that spot
I'm trying to draw an XYZ axis and label for an empty gameobject in the editor window.
The sphere is a Gizmo so that I can click it and select the object.
The sphere and axes are also Gizmos so that they are hidden by objects in front of them.
I'd like to use Gizmos to draw the label as well, but it seems that you can only do that with Handles.
My problem is that the Handle.Label is always behind the gizmos.
How can I draw the label on top of the gizmos? Is there some other way to do this?
public class SpawnPointGizmo : MonoBehaviour
{
private const float AxisLength = 0.5f;
private void OnDrawGizmos()
{
// X axis
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, transform.right * AxisLength);
// Y axis
Gizmos.color = Color.green;
Gizmos.DrawRay(transform.position, transform.up * AxisLength);
// Z axis
Gizmos.color = Color.blue;
Gizmos.DrawRay(transform.position, transform.forward * AxisLength);
// Sphere
Gizmos.color = Color.white;
Gizmos.DrawSphere(transform.position, AxisLength * 0.25f);
// GameObject name
Handles.color = Color.white;
Handles.Label(transform.position, gameObject.name);
}
}
Have you tried zTest?
https://docs.unity3d.com/ScriptReference/Handles-zTest.html
Yes, I tried a few of the options for that, but it didn't help.
It also says Default value is Always., which I took to mean it's always supposed to be on top
I'm assuming that Gizmos just aren't included in the zTest.
Edit: I tried all 9 of the CompareFunction options and none of them drew the label on top of the gizmos
Here's the setup I used
Handles.zTest = UnityEngine.Rendering.CompareFunction.Never;
Handles.Label(transform.position, gameObject.name);
i believe i see what you mean now, given a big enough red circle it might not always work
shot in the dark- for the handles: Handles.BeginGUI(); GUI.depth = 1; //stuff Handles.EndGUI();
No change unfortunately. The sphere gizmo is still on top of the handle label.
// GameObject name
Handles.BeginGUI();
GUI.depth = 1;
Handles.color = Color.white;
Handles.Label(transform.position, gameObject.name);
Handles.EndGUI();
Oddly, if I put the gizmo behind an object, then it will show the label on top.
I guess that's because the gizmo gets occluded but the handles don't
Your issue is, you want to show the gizmo on top everytime?
I want to show the Label on top of everything. It's a Handle instead of a Gizmo, and the Gizmos are showing on top of it
As far as I know, the only way to show text in editor like this is with Handle.Label
Cant you just offset the label in z axis towards the camera?
I suggest not using label then. Maybe something like this https://gist.github.com/Arakade/9dd844c2f9c10e97e3d0
That sounds like it might work. I'm not sure how to translate the position towards the camera like that
^ not gonna be Z axis in world space if your camera has turned- but I agree .. moving toward camera is a good idea.
-camera.transform.forward would work tho
yep, but as said, you could also just not use Label but use GUI and draw on top of everything with the script I pasted. different approaches
Making an RPG: In the past I had used enums to reference and figure out which stats to effect by code, and them being a hard-coded allowed me to directly reference them without issue. At some point it was suggested either by tutorial or a video or whatever to use ScriptableObjects in place of enums, so I was wondering if anyone had input on replacing enums with SOs for the purposes of something like stats in an RPG?
To be clear I've already been using SOs to at least initialize them, but I've reached the point where its becoming a bit tricky to deal with as I can't hard-reference certain things that I would normally need to. Was hoping someone had some thoughts as to the design philosophy
The way to access each stat would still be "hard" coded in an SO, they would be the names of each of your stats, as a member of the SO derived class. But honestly , I'm not quite sure what your doing with the enums.
If you are using SOs as Data Templates, you have to make your methods work in a more generic way. Instead of switching through an enum, you rather just have a method that handles your dataSO and just uses that data. Now you have to separate the selection of your datasource to another point in your script that passes in the correct SO to your method afterwards.
One way would be to use Linq and call .ToArray() on Knots, then access the index that way, though the position I know is not a Vector3, rather a float3 so you may need to convert or use each individual axis as needed, otherwise I think the type being a IEnumerable there may be other ways to access it
Are you planning on changing the SO values on runtime to store stats or just as template for base things like items or character roles?
Well for example, my SO for a StatType declares a localized string name for the stat, min/max value, and a start value. I have one for things like MaxHealth, AttackSpeed, and so on.
The thought process originally was if there was a stat I hadn't considered that I may need, adding it would be as simple as creating a new SO.
But I'm finding it difficult to sort through them for a specific stat, leading me to think of things like sorting through all the SOs for things like an "ID" which then resembles me hard-coding it anyway.
So you want to add the "Attribute" Health as a new SO, later maybe the Attribute AttackSpeed and so on?
In this case, you would rather have to categorise your attributes to get your values taken into account rather then hardcoding the attribute itself. You gotta decide some base values in the end, otherwise you would try to make a full generic system which is not going to work well ๐
I wondered as much. I guess I'm still not confident in my coding skills despite my years of doing it.
It is more about deciding at some point. Maybe refactor later as you learn that the system is not fitting your needs. But trying to make it generic all the way from A to Z because you are scared to make something wrong will just block your progress
This is what a Dictionary<K,V> is great for- you can replace K and V with any types you want.. e.g K could be an int/a string/an enum/whatever, and V could be a reference to your attributeSO.
as long as you are consistent with the keys, you could even save them, rather than the whole SO object- when you save the game state
I use Dictionaries a handful, as it turns out. I have some DamageTypes connected to a DefenseStat class so that I may sort through quickly for whatever relevant defense is needed.
ah, I must misunderstand the goal ๐ญ
Finding that my "attributes" simply aren't a good fit for this methodology though.
I mean thats basically what I was doing up until now for them
You might want to combine that enum with a scriptable object. You might have the Health type in your enum, and you can create SOs with that type that affect your health. But base values as a SO does not sound the best way, actually thinking you can add base elements later on does not sound like the right thing to go for, but maybe I am missing something
No, I had been ruminating on the thought of things like Health or AttackSpeed being separate for a bit now. It'd make things much simpler/easier/faster to work with, and its doubtful that I'll need to worry about it too much later on.
Thank you all for the correspondence, you've been most helpful.
so, you create an SO that is a StatType and it's the name of the stat, is that correct?
Among other things, yes. As previously mentioned, Min/Max stat amounts and base amounts.
sorry, just joined, what problems were you having with searching for a stat?
While I could search for a stat, it'd be little to no different than hard-coding it in the first place.
using an SO as an enum is not a bad way of doing things. i do smth similar. makes it easy to add any amount of types without needing to update a file or an enum . . .
Yeah the conclusion was that it wouldn't work well for replacing core gameplay stat mechanics; i.e. max health which may need to be later referenced directly as opposed to "searched" for.
I tried a couple of the solutions in here and they had the same issue, the Gizmo spheres draw on top of the Handle labels.
I tried moving the labels closer towards the camera, and it is also not making a difference. @clever lagoon
Handles.color = Color.white;
var view = UnityEditor.SceneView.currentDrawingSceneView;
Handles.Label(transform.position - view.camera.transform.forward, gameObject.name);
I appreciate the help, but it is looking like Unity just draws Gizmos on top of Handles here.
In that solution they are using UnityEditor.Handles. Is there a different way to draw text in the editor aside from Handles?
The problem is the wish of being able to extend the base stats later on with new stats but nowhere in the code are they referenced then (what he means with hardcoding)
GUI.Label is another option
i think the problem is how your base stats are modeled or the access to it. you can have a c# Stat class and a StatType SO to use for the name of any stat(s). any script that needs to access a stat will have a reference to the StatType SO and it'll pull the corresponding Stat from your dictionary (if i understand your issue) . . .
Imagine he wants to add MaxHealth as stat but later on another state like MaxAttackSpeed and so on. Like a full generic way of setting up the base stat system.
you mean later on during gameplay or in the development process?
I think he means on development process, probably
is it possible to somehow query unity services player accounts from asp.net core server to authenticate users making api calls?
The issue is, that he has to hardcode at least a switch or something to know what the stats are for. ANd it sounds like, he is not quite sure about his own system yet, as it might hold anything from health relevant to attack relevant stats. I suggested combining SO and enum, so the SOs have stats and a enum for the type they target like health or attack base stat. But if the goal is to also create those base stats based on SOs, thats gonna be a hard time
Are you talking about API Calls like oAuth ?
that what it will do. i just have a list of stats. when i want to add a new one, i add to the list, which creates a new Stat and then i drag the StatType SO that represents the name of the stat. during gameplay, it creates a dictionary based on the list using the StatType SO and their associated Stat class . . .
yep, i want server to provide stuff that unity services cannot do
But you did categorise the stats at some point, right? Or can you character hold Health, Endurance and another Character hold Health and Strength but not endurance?
probably what i wanna do is impossible since players need to be able to play without login via anonymous authentication to unity services, but maybe it exposes some tokens for these "local accounts"
so users cannot perform web api calls in behalf of another accounts
Then you might have to read about tokens and logins and see if Unity API gives you any oAuth option to get a token you can then use to create a user on your server based on that information
user is there on server but i dont want to hold login data, only limited authentication based on unity user ID in token or something
Did you read about unity game services then?
another developer is kinda responsible for it for now, i have limited knowledge ๐
well he should assist you then, because those services are actually the portal for what you need Id say
- no, the stat does not know if it represents Health, Endurance, etc., the
StatTypeSO you assign to that stat does - yes, you add whatever stat(s) you want for that object (using a
StatControllerclass: this can be derived to specific controllers, like aGunController) . . .
where ?
yeah, you assign teh SO to a stat, so that StatType is known upfront, correct?
yeah, in the editor during development . . .
Okay, so I think we have to know, does he just want to create them on dev, which is possible as you said.
i mean, if you're creating a stat, you have to know what the stat is for, that wouldn't make sense otherwise . . .
And I am not sure, this is the case in the current OPs thoughts ๐
@marble fjord (message was deleted so i lost the reply/mention)
these questions can't simply be answered as they depend on how the character controller is coded/designed. performance is based off how you write the code, not so much with method is used. your pseudo-physics can be more cost intensive than regular physics
you'll always encounter glitches when working with physics and fast or large-moving objects. you test and set limits to avoid these issues. also, nothing will be glitch free
you can have full control using a physics-based (rigidbody) character controller or writing your own. you will still encounter glitches with your own character controller; not using physics or part of it does not omit any controller from that
the only concrete answer i see is physics should be limited or carefully maintained if developing on mobile . . .
mouse click event is not working ?
because im using a render texture in my camara
is there any other way to mouse click event in render texture?
You could use a second camera that receives the input for example.
Whats the best way to have different build modes, eg. I want to do a slightly different version of the game - one for my level editor to use, one for my artist to easily replace assets, a Demo build to upload to steam etc. etc. I was thinking of something where I can make Unity set preprocessor directives just by choosing a different build option, eg. "Demo build" , "Level editor build" etc,
Please help me i want to disable automatic clean scene after every test. Chatgpt said something like that but i dont have this option ๐ฆ
Open the Unity Editor and go to Edit > Project Settings > Editor.
In the Editor Settings, scroll down to the "Test Runner" section.
Uncheck the "Exit Play Mode After Test Run" option.
Click the "Apply" button to save your changes.
Maybe look at the docs instead..?๐
i tried
Is Unity ECS actually good to use now?
It's still not out of preview
Alright but that doesn't aaaaalways mean bad to use ๐ค
Good from what perspective?
i tried its not working
This does not seem to be coding related, so maybe #๐ฒโui-ux and get some details in that channel how you are using the rendertexture exactly
How do i make my character run speed increase as time goes on? like in temple run
this is my current code for the movement and speed
!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.
Oh sorry
Im new to this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
if (listPositionKeys.Any(item => item.key == _listPositionKey))
{
}``` Is this a lambda expression?
Does anyone have a link to a good outline package on asset store? Or is there a pre existing unity solution to produce an outline?
I'd like a blurred outline on 3d objects
Try asking in #๐ปโunity-talk or #archived-shaders
I have a class that looks like this: csharp public class ListPositionKeyData { public string key; public int listPosition = -1; }
How can I do something like this: csharp int index = listPositionKeys.IndexOf(item => item.key == _listPositionKey)? I want to get the index of the element in the list of ListPositionKeyData where key == _listPositionKey
If listPositionKeys is a list then .FindIndex
Anyone have experience getting CPU profiling to work with Pix? I can't seem to get it to read the PDB files ๐
I've tried adding all the paths I can find with pbd files in them.
Yet all I see is this
When looking at sampled functions
(I'm using Pix here rather than Unity profiler since I want to do a sampled function profile)
When I tried using VerySleepy it correctly displayed the function names to it feels like I'm just somehow failing at getting Pix to understand where to find the symbols
I think I figured it out
Apparently I had to add a source path to <game_root>\<game_name>_BackupThisFolder_ButDontShipItWithYourGame\il2cppOutput
can someone help me find why I'm getting this error? I don't call SendMessage at all in any of my scripts, and I don't think any of the plugins I'm using do either. Is some other function I'm calling invoking it or something??
Well if you look at the full stack trace you can see what's causing it. Appears to be Unity editor related at first glance
this is all it says (if this is what you mean)
It seems to be called from OnspriteTilingPropertyChange. Is that anything your plugins use?
I don't think so, even then I'm using a lot of sprites and it only seems to be happening when i create new prefabs with sprites (the 2 ones being affected now), it hasn't affected any of the sprites I had before. I can't recall any plugins I installed recently either
So you create a gameobject, add a sprite and make a prefab out of that which fires the warning?
Id say this is a bug, you might call something on OnValidate or Awake or something, that triggers this or your plugins do
Thank you ๐
Wait no
Umm
I have a string that matches a variable of one of the list elements. I need to find the list element with the variable that matches.
Ok I think I actually found why it's doing that, its not when I create a new object its when I'm adding it to a statemachinebehaviour script in the inspector like this:
Once i remove it i don't get the error, but I don't do anything in Awake or Onvalidate or whatever unless its doing it within the statemachinebehaviour by default
Can you elaborate?
.Find
Yes. Something like this. Is there a super simple way to do this? csharp List<string> keys = new List<string>(); for (int i = 0; i < listPositionKeys.Count; i++) { keys.Add(listPositionKeys[i].key); } int index = keys.IndexOf("My Key");
The listPositionKeys have other variables than key too. I need to find the one from only knowing the key
So I can get the rest of the information
Like Nitku said, .Find .FindIndex or just a simple for loop
How can I use find and findindex for this?
I think I probably don't understand what they do. Can I pass in a parameter to look for in .Find? I thought I needed it to be the same type as the list elements
listPositionKeys.Find(i => i.key == "My Key");
Literally this code but replace IndexOf with Find
Wow. Okay, thank you so much. I totally misunderstood ๐
Thank you both ๐ ๐
Hi, anyone know how I would add a new item to the create context menu in hierarchy, inside UI for example?
Judging by this post: https://forum.unity.com/threads/simplest-way-to-add-an-option-to-right-click-menu.424987/ the question probably belongs in #โ๏ธโeditor-extensions
I'll have a look at it thank you
Why would any of these instructions replace my mesh (on meshFilter) for an instance of the mesh?
var colors = mesh.colors;
var triangles = mesh.triangles;
int triangleIndex = hit.triangleIndex;
var c0 = colors[triangles[triangleIndex * 3 + 0]];
var c1 = colors[triangles[triangleIndex * 3 + 1]];
var c2 = colors[triangles[triangleIndex * 3 + 2]];
float red = (c0.r + c1.r + c2.r) / 3;
float blue = (c0.b + c1.b + c2.b) / 3;
float green = (c0.g + c1.g + c2.g) / 3;```
ChatGPT answer: None of the instructions you provided should replace the mesh on the meshFilter component. These instructions are simply retrieving data from the mesh and performing calculations on that data. However, if you have other code that modifies the mesh or the meshFilter component, it could potentially replace the mesh at runtime.
Thats what i thought, but commenting those lines erases the problem, the rest of the code is just reading the red blue green floats and playing a sound that
{
return Surface.Grass;
}
if (red > VertexColorTolerance)
{
return Surface.Path;
}```
Its just that
What about this?
the only code left, i then have a switch that plays a sound and thats it
It replaces the meshFilter for a mesh Instance
So the collider and the Filter dont match
also this is the only new code and i never had this problem before, so it has to be. (It doesnt interact with anything else, its just a sound player)
This ain't the problem too
Hello Unity peeps, is there a component for motion blur and animation frame rates?
When does Unity create these mesh Instances by itself?
By itself huh
I didnt write any code for it afaik
Cancel that, found the answer
I'll dm you that
I create screenshots using a renderTexture and save them as png, as a result of my approach i get transparent borders around my image (need to make the camera big enough so that different things are always in the frame), is there a way to remove these transparent borders somehow?
I also noticed the colors are different than whats seen onscreens, so i am not sure what todo about that
public void saveScreenshot()
{
foreach (var hideObject in hideScreenshotObjects)
{
hideObject.SetActive(false);
}
gameObject.GetComponent<RectTransform>().position = new Vector3(1372, 720, 0);
gameObject.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
mainCanvas.renderMode = RenderMode.ScreenSpaceCamera;
mainCanvas.worldCamera = cam;
RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = cam.targetTexture;
cam.Render();
Texture2D Image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
Image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
Image.Apply();
RenderTexture.active = currentRT;
var Bytes = Image.EncodeToPNG();
Destroy(Image);
File.WriteAllBytes("Screenshot.png", Bytes);
mainCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
counter = 0;
foreach (var hideObject in hideScreenshotObjects)
{
hideObject.SetActive(true);
}
}
Returns either a new mesh or a duplicate of the existing mesh, and assigns it to the mesh filter.
https://docs.unity3d.com/ScriptReference/MeshFilter-mesh.html
sharedMesh doesnt do that
Ooooh ff
That must be it let me try
Shared mesh modifies every object with that mesh
Same for anything Shared like materials
I dont see them modifying it, just reading
And reading shouldn't cause instance creation
Oh wait nevermind I just read his code
It works yesss
What do you mean with "shouldnt"
Nothing
It should, according to documentation
I hadn't read the code
Correctly
You are right
Isn't it the same for materials?
np guys its working, the return did indeed make an instance and assign it as the docs say. Just not in the mesh collider just the mesh filter ๐๐ป ๐ฅน
Its similiar to renderer.material vs renderer.sharedMaterial, yes
Hm
appreciate your help have a nice day
Hello, i have an event that doesn't seem to get fired or it does but the subscribed function isn't getting called
This is a part of the code in my script handling general events, it is a singleton but also has static events since i ran into an issue with the update cycles so needed to make sure the events were accessible at any time.
public static event Action OnPause = delegate { };
public static void Pause()
{
OnPause();
}
This is a part of the script for my pause menu
private void Awake()
{
GameEventsManager.OnPause += ActivateMenu;
}
private void OnDestroy()
{
GameEventsManager.OnPause -= ActivateMenu;
}
public void ActivateMenu()
{
Debug.Log("The activate menu function is called");
this.gameObject.SetActive(true);
_resumeGameButton.interactable = true;
_mainMenuButton.interactable = true;
_quitGameButton.interactable = true;
}
So i tested with some debugs and in the function Pause() the debug message get's called but after that it can't work it seems
I think it's probably the subscribing were the issue lies i assume
Not sure what you mean with the transparent borders. Would changing the texture's wrap mode to Repeat help?
This is how a subscription looks like
private void OnEnable()
{
GameEventsManager.OnPause += HandlePause;
}
private void OnDisable()
{
GameEventsManager.OnPause -= HandlePause;
}
private void HandlePause()
{
// Do something in response to the pause event
}```
can i post a screenshot here?
i get transparent borders and the colors are wrong, its not supposed to be that saturated
and these dark blue icons i added are way too dark aswell, not sure why
this doesn't seem to be different than what i have
I think you should set the camera to orthographic and match its size to the map
Yeah
i changed to on enable and on disable and it is the same
there are different maps, need to figure out a way to dynamically change the camera then
But what could the problem be with my subscription, it's a static event so i don't think it should be a problem
I have an asset bundle which I want to reference it in a script. If I put "public AssetBundle myAssetBundle" and then try to add it from the inspector, I cant.
nvm, i forgot to mention that everything is on the UI layer, so ortographic doesnt do anything here
Where do you set the size of the cam.targetTexture?
that's a texture i have in my resources folder
Okay, then you probably need to match that texture's size to your map
Is it correct that Awake isn't called on disabled gameobjects that are disabled in the editor so at the start of the scene/game?
yes
its a good idea to treat edit-mode disabled game objects as if they don't exist by your runtime
Yeah, i will make more use of disabling in awake or somethng if they don't need to be active or another method.
I just had an event i needed to subscribe to for my pause menu but the menu was disabled
its a very useful property that if you break it can make handling your project much more annoying... just my experience... might not apply in special situations
yeah, it's just in this specific case that it wasn't that useful
i've found that disabling components is the more useful approach to disabling behaviour
You can also separate the visual aspects from the logical aspects. E.g. leave the root object enabled with its scripts etc but have the visual elements all under a child object which is disabled
Yeah, i will do one of those in the future
Off the top, can you guys think of a cleaner way of doing this other than just having a method only for that in the _deckController?
while (_deckController.RemoveCardByKeyword(Keyword.DISCARD)) {}
It returns true if a card was removed. Is this that bad?
Not sure what exactly you think is "bad"? I just wonder about the while loop for smoething, that sounds like a trigger, but besides that
I don't get what you mean in the second part
It's hard to say without seeing more. I'm assuming there is a reason you are using a while instead of an if. But the slowdown is going to be in the desk controllers code if there is a slowdown. In of itself, as long as that isn't in an update, I'm sure it's fine.
I'd probably go a different route and use an event when a card is removed, but I'm sure it makes little difference in functionality
And I don't know, I usually try to avoid those for some reason
Alright, yeah I guess it just looked unusual to me, I'll go for it!
if i wanna make an entity go to a specifc coord, do i just add the force forwward to the entity in the direction in which the position is and stop it when it reached it?
does it seam like a good idea?
or is something better
While statements are risky because they can lock your editor.
You say, this returns true if you remove a card, that "remove a card" sounds to me like a thing that happens and is done, no ongoing action, thats why I called it a "trigger" and was wondering about a while loop
can't you make them syncronized?
That's pretty common.
oh really?
i never got interested in seeing how it's done
i just assumed that's how
Yeah, one of our VR flying games, we abuse the bejesus out of add force. The client wanted a lot of unusual specific mechanics (bout 15 specific formulas he wanted to apply depending on hand movements), so manipulating the force that way was the best way while preserving physics
oh alr, thx
Can someone point me in the direction of an algorithm? I need an algorithm that is similar to A* search, except that it searches for tiles within a certain distance. All tiles reachable within fx. 5 moves should be returned
Just use BFS with a depth limit
Dijkstra's algorithm can work if you implement it yourself
or perhaps theres an existing implementation
there is a github repo with examples, but its 4 years old, not sure its still relevant
Djikstra is basically a modified DFS/BFS with edge weights and a shortest-path table
but they don't really need shortest path
they just want to get the list of tiles
Thank you both all for the suggestions ๐
Actually I just wrote this for someone on here the other day
exactly the same problem you are solving
they wanted to highlight walkable tiles in their hex grid
Wow! I am so lucky ๐
ofc it assumes some things specific to their grid implementation
o you'll have to adapt it
but it's just a BFS with a depth limit
Thank you. I really appreciate it
one thing you won't have is the neighbors() function
but it's just a function that returns the neighbors for a given coordinate
all 6?
yes
alright
hey guys, im having some trouble with 2D collisions not firing
https://unity.huh.how/programming/physics-messages @magic harness
What is my set-up?
2 prefabs with 2 childs each. Each child has a trigger and a script attachted to it.
The prefab has a kinematic rigidbody 2d
layers are set to collide
i have tried disabling trigger and just seeing it if collides, and it doesnt
just went through all if that troubleshoot and still nothing
i am moving it using transform.position
but it is kinematic, so it shouldnt matter
i just need the trigger to fire
at least in the scene view, the collider moves correctly with the game object
im very confused
if you use transform.position, you ignore collisions
and are the colliders the 2d version of it too?
follow the guide here #archived-code-general message
Ahh thanks for the link, I just couldnt find the unity how to thing ๐
it was probably cause i was using transform.position
but not it just moves to 0,0 at start
things dont move by themselves unless with gravity ๐ so you seem to set it somewhere.
they are kinematic
So maybe you show your current script and where you debug log that it is not hitting
so this is my move function which gets called on fixedupdate
protected void Move(Vector3 goalPos)
{
Vector3 direction = (goalPos - transform.position).normalized;
Vector3 nextPos = direction * moveSpeed * Time.fixedDeltaTime;
body.MovePosition(nextPos);
}
and this is my very simples message callbacks
so... debug.log in the trigger enter is working actually. but they are just instantly moving to 0,0,0 position on start. kinematic rigidbody2d and gravity set to 0,0,0 in project settings
did you debug log your direction and nextPos ? I assume they are 0 too at some point
shouldn't this be:
body.MovePosition(body.position + nextPos);```
MovePosition takes an absolute new position
not a direction to move in
also nextPos is kind of poorly named - as it's more like a movementVector or positionDiff, not a position outright
private void FixedUpdate()
{
Vector2 playerDirection = (Player.position - transform.position).normalized;
if (Vector2.Distance(transform.position, Player.position) > 1.6f)
_moveBody.velocity = (playerDirection * _speed).WithY(_moveBody.velocity.y);
}
so i am trying to make an enemy follow the player with an offset,but it keeps alternating between the player's right and left,any idea how to fix it?
brb video is black for some reason,gonna rerecord
you're setting the velocity - but on the frames you DON'T set the velocity, it's going to just keep flying in the direction from earlier
because of newton's first law of motion
"An object at rest remains at rest, or if in motion, remains in motion at a constant velocity unless acted on by a net external force."
if (Vector2.Distance(transform.position, Player.position) > 1.6f)
_moveBody.velocity = (playerDirection * _speed).WithY(_moveBody.velocity.y);
else
_moveBody.velocity = Vector2.zero.WithY(_moveBody.velocity.y);
would this work?
i mean... sort of? It's going to be very stuttery
also you didn't mention before but it seems you are only interested in the x position for this?
I dont know if this comes under coding, or it might. But does anyone know why this happens ?
most likely an internal unity editor bug
I see, how does one fix that ?
yes
Nobody can fix it except Unity
so how would i stop the stuttering?
you need to adjust your velocity to make sure it's not going to overshoot the offset
Right, buttt its stopping me from working, is there a work around :?
how is it stopping you from working?
Turn off Error Pause in your console
sorry,but what do you mean?
I mean I did that, u mean click error pause right ?
In your screenshot, error pause is enabled
that's why your game is stopping whenever that error happens
turn it off to stop that from happening
Alright did that, but now the game is super laggy :/
The error looks like a memory leak 
ahhh I see, how does one fix that ?
Go through all my scripts and try and fix them>
could that be doing it
Probably unity itself, try googling that error
any unity dev with regards to generative ai?
Hi ,
what is the equivalent of Math.Round() in unity ?
I ran the profiler and found this ?
Math.Round() has overloards , but Mathf.Round() doesnt
is there is any other alternative ?
Something under LogStringToConsole
What are you trying to accomplish
round a float to 2decimal or 3 or 5 .. etc
based on the equation
It higlights Math as unknown , do I need to add something ?
Take a guess
and maybe mouse over it
and see what it says
you should be used to fixing this by now ๐
oh yeahhh ๐ , thanks actually , i need to trusth that hint ๐
I remember when I first started to learn C# that tip used to do things and add drivatives that I didnt understood and scared me, so I stopped using it all together lol, I will start trusting it again ๐
Thanks alot โค๏ธ
Just clicking in the editor gives me them error messages
Alright so I have restart unity and see if that fixes it, it has for now. I dont know if that is a full fix
Restarting can fix quite a few unity issues sometimes
Unity's terrain system providing memory leaks comes to mind
You think its the the terrain ?
No, that was just an example
Idk how long ago that was, but it used to have memory leaks
Ahhh I see, alright. well I think I might know what the issues was. I think it was the old first person controller ?
because I moved my game from 2018 version to the 2021 version
Nope it happen again
Do I just drop down a version ?
Is there anyway to make an overlay camera use an oblique projection matrix?
You can assign any projection matrix you want to any camera in Unity: https://docs.unity3d.com/ScriptReference/Camera-projectionMatrix.html
im trying to upload a build to oculus dev hub but it gives me a API error
thanks
I do already have the projection matrix that I need applied to it, but it doesn't seem like it's being taken into account for the overlay.
the fact that it's an overlay camera isn't really a factor
Simply changing the near clip plane does have an effect, but I don't want it to always be flat, so I need the oblique matrix.
I'm using it in a camera stack. The preview for it is using the custom clip plane, but the image being stacked onto the main camera's view is not.
How can I find the element of a list with the highest value using a .Get() method on it in LINQ?
I know I want to use .Max (default list method) and .GetHP (specific to my context).
I know how to get the value, but I want to get the object itself.
This is how I would get the value in case it helps:
opponents.Max(o => o.GetHP());
Hey there folks, I've created a few math-related methods for myself that I can use for a bunch of different scripts, so I'm planning on putting them in a separate script where they can be called. Should these go in a struct or a class? I was planning on a class, but then I saw that Mathf uses a struct so I'm not sure anymore.
I would use a static class
Not sure why Mathf is a struct or if its common for these kinds of method collections
If someone knows the reason let me/us know
Looks more mathy, obv
I don't know the reason. There's no difference in performance or anything like that. But in my IDE theme, structs are a different color than classes, so Mathf is the same color as Vector3 and etc... Which I like, but ๐คทโโ๏ธ
LINQ doesn't have a built-in way to do this, so I would recommend just doing it manually in a foreach. There are workarounds to get it working with LINQ, but they will be much slower than doing it manually.
Hahah okay so its just a relic. Thanks ๐
Sometimes I forget how old unity is... 2007 damn
Good to know, thanks!
i remembered i bookmarked this post for the future so i could look at it again but i forgot about the bookmark and never looked to see if it had an answer but iโm glad it does ๐
pretty interesting
Oh that makes sense
so wondering, but is there any way I can overwrite the default behavior of serialization? so specifically for my case, I have a struct called UnlockableId and its pretty much a wrapper for a string. the problem is that when I apply Serializable to the struct, in the asset hierarchy it serializes like this:
_unlockableId being the field name thats to be serialized, but itll serialize the _value under it
is there any way I can make it so that itll be morelike _unlockableId: {value} rather than it like this?
same deal on deserialization
How can I automatically subscribe to a public event (like OnClick() for the UI button) if I have a reference to the instance of the object with the script that has the event?
No, I've never heard of a way to customize serialization to that degree.
its in yaml so im trying to see if I can overwrite its serialization/deserialization behavior
You could probably overwrite the yaml afterwards, but how are you going to convert it back just before Unity reads it again?
Can you elaborate on the automatic part? Would if object not null, OnClick.AddListener code in your other object not do?
Serializable will serialize all members, including privates
But its not the only qay to serialize things
thats sort of what im trying to figure out, a way to have it read/write differently so when it tries to fetch it afterwards itll implicitly convert it to the struct
OnClick.AddListener
Thanks!
Why do you care what's in the yaml?
also another reason i want to do this being im setting these values to firebase, so i dont want there to be a bunch of _value fields
^ biggest reason being this
firebase is json serialization so im confident i can customize that behavior before i sent out the request though
Why do you want to rely on Unity's serialization for this instead of rolling your own?
hmm fair, something i should consider
also do note, i dont plan on directly sending out the entire yaml string to firebase or anything lol
but fair enough, ill make some changes
private void Update()
{
if (IsCloseToPlayer && Time.time >= _nextAttackTime)
{
var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer);
OnAttack?.Invoke();
_nextAttackTime = Time.time + 1 / _attackRate;
}
}
so i am trying to make it so that enemies attack the player when he is close to them,but they have a weird attack pattern,any ideas why this is happening?
I usually use container objects for serialization but tbh ive never built a full scale save system. Usually thatbwas only fornsingle components
this is for saving objects to firebase, so i need it to be as small and lightweight as possible (hence why im trying to remove the redundant field)
In my experience using extra containers was the rught thing to do, since loading/saving is notnsomething you want to clutter your class with
And it makes mocking data for testing easier too
we arent making a save system
Any help anyone?
wdym by "weird attack pattern"?
in the video
I watched it
wasn't sure what I was looking at exactly
it seemed like it attacked on a regular interval
it randomly attacks when the player leaves and when the player is still close,it doesn't attack
but you also moved your character at that same interval
well you're not really sharing enough code to make sense of it
We'd need to see the rest of the script
private static Transform Player => GameObject.FindGameObjectWithTag("Player").transform;
private bool IsCloseToPlayer => Vector2.Distance(transform.position, Player.position) > 1.3f;
public event System.Action OnAttack;
[SerializeField]
private LayerMask _playerLayer;
[SerializeField, Min(0.01f)]
private float _attackRate = 1;
private float _nextAttackTime;
private void Update()
{
if (IsCloseToPlayer && Time.time >= _nextAttackTime)
{
var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer);
OnAttack?.Invoke();
_nextAttackTime = Time.time + 1 / _attackRate;
}
}
this si what is inside the class
private bool IsCloseToPlayer => Vector2.Distance(transform.position, Player.position) > 1.3f;
this seems like it does the opposite of what its name is
it's checking if you are at least 1.3 meters away from the player
don't you want < instead of >?
let me see
(also this line var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer); seems to be unused entirely)
it will be used when i add the health system
how so
you already have a reference to the player
Oh I see it's the attack range or whatever
well it worked,thx
Hello, im making a 2d platformer and want one part of the collider of the tilemap to be disabled when if press "s". Can anybody help me?
I found this: https://www.youtube.com/watch?v=Lyeb7c0-R8c
In this short tutorial we will have a look at how to create one way platforms - ones that you can jump through and how to allow player to fall through them by pressing the down button. I hope you enjoy it :).
Got any questions? Join our discord:
https://discord.gg/hrZF93sCkc
#UnityTutorial #Unity #Platformer
Feel free to join our discord: h...
Yes, but does this work for parts of a tilemap? Because i cant add components to them
Got a bit of a problem i need solved.
I have > 25 "units" in my game.
on the prefab of each unit i have a camera that is assigned a RenderTexture as a target texture that is created via code when the unit is instantiated.
This rendertexture is then used in my canvas to display sort of what units are selected during runtime.
This is working great, exactly as i want it.
Now here's the problem.
All the cameras ofcourse render all units, not only the parent unit that it is attached too.
I thought of using the Culling mask option of the camera to only render the specific unit. But that'd mean that i have to create some +25 layers for each of the units.
Is there any better way of doing this?
dunno how that would work with tilemaps
- Set all the culling masks to render the "snapshot" layer only.
- Before rendering the "snapshot" to the RT, move your unit to the snapshot layer
- take the snapshot
- move the unit back to its normal layer
only one of them will be in that layer at a time, so the culling masks will work
hm. good idea. But will the rendertexture change over time then? or do you mean to just take a "snapshot" to get a still picture?
I assumed you meant still pictures
oh no, i want live rendering of the units
otherwise id just make an icon in photoshop or whatever
Cant figure out how to do it still x) tried something, but didnt work. To be fair i dont quite understand the "-Before rendering the "snapshot" to the RT..." part
do you mean move it to the snapshot layer before i call Create() on the rendertexture?
When was this added to C#? csharp List<Transform> objs = new();, specifically the csharp = new();
Wait nvm, its 9.0
I'm on 8.0 still ๐ซก๐ซ
This thing is only going to work if you're taking snapshots
You could also do it with manual Render calls on the cameras
but it's going to be really slow
guys Idk why is my character behaving like that
All I added was a RB.AddForce ; but even removing it won't resolve this... help
looks like your code is messing with the vertical velocity
possibly setting it to 0 each frame
I bet you one chicken nugget it is
adds, doesnt it?
show your code
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Post code this way^
yeah you have something else in the scene causing this
some script on a different object
and what is it^
um no
cant even get the snapshots to work lol.
I don't
you must
I don't have other scripts that could mess with it
copy mario into another scene
okie dokie
also show what the script looks lioke int he inspector when you select it
maybe you forgot to save your changes
Like what's this "Player" script I see in your assets
Player script? You mean MarioMove?
ah that one
it just gets the new input system
btw Mario in a new scene works just fine
maybe smth with that camera script... let me check
sounds likely
like I said - probably one of your other scripts
I'll show you them all while I check wich scripts mess up the whole thing
show the camera one
RB.position = Position;
bruh
you're doing this
every frame
and you're confused about why you're seeing what you're seeing??
It doesn't matter where the script is
I belive
- Why on earth would a camera have a Rigidbody
- You're doing FindObjectOfType<Rigidbody2D>()
What is this for? cs out neighborDepth
that will find ANY Rigidbody2D
On line 13
not just the one on that object
okie dokie ty
just grabbing the existing depth from the dictionary for that coordinate
Sorry that can just be out _ @rustic ember - we don't actually care about it
I'm trying to make a 4-track audio player that lets you swap out different "stems" of a song in real time, but I'm running into issues with getting the total amount of "beats" elapsed since the start. Since you can change the tempo in real time, I'm using
beatsSinceStart += Time.deltaTime * tempo.value / 60; which works on lower tempos but gradually becomes inaccurate with faster ones. is there any better way to do this?
Right, that's what I thought. Does TryGetValue always need an out?
Looking back that line should just be this:
if (depths.HasKey(neighbor))```
yes
that's how it returns the value
but we're not using it
so HasKey is better
Right, okay. Thanks again ๐
oh nvm AudioSource.timeSamples exists
yea you should use this and/or dspTime whenever possible
I think it's ContainsKey on C# 8.0
plausible
Unless that is something differnt
oh that's what I needed!
thanks
ahah okay. Where all the best knowledge is from'
Ty @leaden ice now the rigidbody works as usual
actually managed to get memory leaks in a language with a garbagecollector. wonderful, good job me
actually managed to create the effect i wanted. Using what you said about snapshotting and manual render calls on the camera. I'm not noticing any slowing down in my game either.
Hats off to you for the idea, thanks!
Is a Queue any different than a List where you .RemoveAt(0)?
not to my knowledge
Alright. Thanks
there might be some internal optimizations to queue tho. Since its kind of designed for that kind of thing.
Right. It looks like Queue.Dequeue() returns the item, while List.RemoveAt() returns void
aye ofcourse, but thats just a quality of life sort of a thing. you can easily make your own dequeue for list
private Item Dequeue(List<Item> list)
{
Item item = list[0];
list.RemoveAt(0)
return item
}
single ` ` around text instead of triple
or if youre using Linq you can use list.First()
or just save yourself the hassle and use a Queue if you intend to have a list that is a Queue ^^
Oh, nice. I like how clean the Queue thing is though
Yeah
yes it's faster.
list.RemoveAt(0) will be an O(n) operation
queue.Dequeue will be O(1) or O(log(n)) or something fast like that
how is not queue a O(n) operation ? ๐ฎ
i may have forgotten something from my class in datastructures...
It's probably implemented as a ring buffer or linked list under the hood
hm, right
with a list, RemoveAt(0) requires you to shift all elements of the backing array
I'll have to look up what a ring buffer is
yea, thats what i asumed Queue was doing anyways
nah it's definitely more optimized than that
when you remove from a list it has to shift all of the following elements down. queue just removes from the end without needing to perform any other operations and it always has a reference to the end position making it O(1)
what about when you put something into queue then?
also o(1)
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1?view=net-7.0
This class implements a generic queue as a circular array
Yep seems like it's a ring buffer
(โฏยฐโกยฐ)โฏ๏ธต โปโโป
ah perfect, was just looking for that
private int _head; // The index from which to dequeue if the queue isn't empty.
private int _tail; ```
Basically it keeps these head and tail index pointers into the array to know where the ends are to add/remove from
What happens when it reaches the end of the allocated memory?
If that is even a thing
that's an O(n) operation but it's amortized across all add operations in the analysis so it's still considered O(1) to add
Damn. Computers are so cool
I guess
Question: I'm using NavMeshSurface collect CurrentObjectHierarchy. How can I in addition to collect all objects from the hierarchy, to also include some cherry-picked gameobjects from outside?
weird I'm still running into tempo issues
void Update()
{
if (started)
{
float totalTime = (float)AudioSettings.dspTime;
float newTime = totalTime - oldTime;
beatsSinceStart += newTime * tempo.value / 60.0f;
oldTime = totalTime;
if (beatsSinceStart >= 32)
{
beatsSinceStart = 1;
}
}
else
{
oldTime = (float)AudioSettings.dspTime;
}
}
could the fact that I'm changing the speed of the audioplayer be impacting precision?
I wouldn't even keep my own timer here.
The Unity documentation for Input.GetAxis states that the value is frame independant. This doesn't mean we won't need to multiply by Time.deltaTime, correct? For movement it's still
float movementX = Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime;
Is there a difference between GetAxis("Mouse X") and GetAxis("Horizontal") regarding this? I've noticed the values for the mouse exceed the -1 to 1 range. Is this a special case? Which line would be correct?
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;```
Mouse axes are a special case
and they are mentioned in the docs
you should not multiply mouse input by deltaTime
it is already framerate independent
Great!
Couldn't you do:
double songStart;
void StartPlaying() {
songStart = AudioSettings.dspTime;
}
double beatsSinceStart => (AudioSettings.dspTime - songStart) / (songBPM * 60);```
yeah but the tempo is controlled independently so I have to integrate it
or just add it every frame
oh right
thanks though! this is really helpful
when you change tempo how does that affect the audio system