#archived-code-general
1 messages · Page 169 of 1
where and how? because your mesh variable is private so no other objects can access it and i don't see you assigning it to any mesh filter anywhere
basically
the triangle list is supposed to have arrays
but its numbers
big fail
where is mesh attached to the specific GameObject?
wait guys
ohhhhhh yes
I haven't mentioned this first time though.
actually that's what boxfriend said before
the object with the script has it
so now it half works
that's cool. you still weren't assigning the mesh to the mesh filter anywhere in the code you showed
the first shape is created
something happens with the second one idk
and the second shape is never visible
yeah sorry
well, because you don't assign it
you mean just mesh's 1st shape is visible?
CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(1, 1), new Vector3(1, 0), new int[] { 0, 1, 2, 0, 2, 3 });
CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(0, 0, 1), new Vector3(0, 1, 1),new int[] { 0, 1, 2, 0, 2, 3 });
the first one is visible
the second one isnt
ohh makes sense
back when it was all I know is that its next to the square that appears
but now it doesnt
try to create just the second shape
yes.
so problem is that you create the second shape on the first shape
so you don't see it
you are supposed to fix it, yes
what does it mean?
it accepts numbers for triangles
but i have a list containing numbers for each triangle
just spawn it on another place?
maybe I should put arrays into the lists
and then iteriate through it
for each triangle
would that be effective
just change vector parameters
what
thats not the issue
wait
can i like add triangles
to mesh.triangles
not set the mesh.triangles
yes.
how
aren't you doing it already?
triangles.AddRange(trs);
no
what's that?
mesh.triangles
thats a list
so?
mesh.triangles is an array. arrays are not resizable, you have to reassign it
mesh.triangles is in a different place
Can you both take it to a thread so you're not flooding this channel?
but the script is not letting me
like
how ma i supposed to put several triangles at once
if i give it a array with more numbers itd oesnt work
w
wait bro then why does this channel exist
To ask and get help, like every other channel.
yes
Great, make a thread since this conversation is clearly going long and so it doesn't flood this channel.
Let's say we have a simple square. When it's at default rotation, the boxCollider2d.bounds corresponds with the collider edges. But when I rotate the object, will the bounds change?
they will change.
so the second image
yes.
thanks
Hi, ive been experiencing an issue when implementing recoil to m gun in my fps game and basically whats happening is that the animation plays on only the first shot and never after it, but when i aim and try again it recoils but again only on the first shot. keep in mind that both the aim a the recoil are animations. relevant scripts: https://pastebin.com/fkqrXRh4
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.
also the animation controller
i think its probably somthing to do with the animation controller
If anyone knows how to use profiler I posted a screenshot in #⚛️┃physics ! Would love help optimizing my game so it is playable! Thanks in advance
(T)Convert.ChangeType(maybeAnInterfaceHere, typeof(T)); vs maybeAnInterfaceHere as T
can anyone help with this?
Hi guys i'm using cinemachine in the starter assets 3rd person and i don't know how to change the sensivity and there is nothing on google can someone help me pls
Cinemachine free look has settings for this in the x axis/y axis bits
i use Cinemachine Virtual Camera but i found the Input action asset thx
the starter assets thing uses FreeLook
if you're doing your own thing, that's separate 🤷♂️
So im working on a multiplayer fps game but the audio is only being played locally so other players cant here sound effects i.e. shooting reloading etc. would anyone know how to fix this? any help would be appreciated.
your audio doesnt look to be networked at all, seems like this script is purely for single player. you'd wanna try #archived-networking or the photon link in the pinned messages there
Hi
Is AR a requirement for a barcode scanner in unity?
Why would it need AR? 
Just a camera should be enough I would think. 
Me too , but looking on google , seems they use ar plugins like vuforia and zxing
Well you probably can do it with those, they also can read camera's/webcams.
But this guys tutorial is super easy and doesn't need it, you would just read the texture of the webcam and check for a barcode in whatever way you would want:
https://www.youtube.com/watch?v=c6NXkZWXHnc
Ok , I'll check it out thank you
Im pretty sure Ive done it before but I forgot, how do I set a gameobjects component to a variable and be able to manipulate that component like you could if you did gameObject.GetComponent<>(), I want to do gameObject.GetComponent<BoxCollider>().SetActive() but i dont want to use getcomponent multiple times, i just want to be able to set it to a variable but still do .SetActive()
Use = to assign things to variables in C#
I know but what type do i use for the variable to get the result i want
Whatever type you're getting of course
boxcollider doesnt work component didnt work
BoxCollider bc = GetComponent<BoxCollider>();
oh
Works just fine
or use GameObject and SetActive false
SetActive is a GameObject function though
it let me do gameObject.GetComponent<BoxCollider>().SetActive(false)
Even if it does that's no different from gameObject.SetActive
There's no need to go through the collider
oh so that wouldnt set the component to false?
With bc.enabled = false
im having trouble with render textures while trying to use a shader graph material
public class TestRenderTexture : MonoBehaviour
{
// Start is called before the first frame update
public Texture2D Icon;
public Material ShaderGraphReference;
public RenderTexture rt;
void Start()
{
var mat = new Material(Shader.Find("Unlit/Texture"));
GetComponent<MeshRenderer>().material = mat;
rt = new RenderTexture(128, 128, 16, RenderTextureFormat.ARGB32);
var frame = new Material(ShaderGraphReference);
frame.SetColor("_Color", Color.red);
Graphics.Blit(Icon, rt, frame);
mat.SetTexture("_MainTex", rt);
}
}``` this just results in a black texture. if i blit just the Icon to the render texture then it will work so its just the material not working. I have set the inputs on the graph to _MainTex and _Color and set each of them accordingly as the main input of that type.
Is it not possible to instantiate a prefab inside Task.ContinueWith closure?
My prefab does not get instantiated, but I get no error in the console.
I have confirmed with logging that that part of the code is reached.
if you are trying to instantiate a prefab in a thread other than the main thread, your thread will be gracelessly killed
Unity doesn't allow things like that in threads other than the main thread
okay, thanks, didnt know about that
so I guess I should send an event that triggers a callback on the main thread?
is this the correct way to do it?
whatver you need to do to get it to happen on the main thread ¯_(ツ)_/¯
Hi I'm trying to make a sensitivity slider and I'm not quite sure how to assign the slider to change my sensitivity. I'm new with sliders could someone possibly help out?
See how i have it passing to the variable button clicked with the => is it possible to have two => without having to do another listener
because i want it to set that variable as well as run a method
button.onClick.AddListener(() => {
buttonClicked = Button;
SomethingElse();
});```
like how I wrote it
Hmm what would be the best and optimize way for finding equal item in a list?
By using a different data structure. Is this something you really need to optimize, did you notice a spike in the profile due to a current implementation?
Without more context, the fastest way would be a linear search. But if we know more about the type of data in your list and how you create and modify the list, then there may be options for more optimizations.
This is a small ScriptableObject and i am getting the items with O(1) and O(n) style. And no i did not see any problem when using LINQ's First() method but i would like to know if there is more optimize way
This doesnt really tell us anything about the list itself, if this is a small list I wouldnt even worry about it
I want to get a specific Collision2D from the scene but the Collision2D field doesn't show up, nor does an array or list of it.
To get faster results you'll need a different data structure or to represent the data in a way where you can cut out parts of the list when searching
!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.
If the data is sorted, you can use a binary search. If the data doesn't need to be ordered, you can use a HashSet instead of a List for faster lookups.
new hastebin link: https://hastebin.com/share/axuxazuneb.csharp
no error codes, nothing
it just works fine
I searched about HashSet but a guy says List would be more accurate for that situtation. I dont know what he meant but it seems the storing strategy thing for each collection is different
Ref: https://stackoverflow.com/a/8110232/20905578
You don't need to use linq for this
nevermind i'm just going to use the colliders
Are you meant the field does not show in inspector?
Try putting [SerializeField] at the top of public Collision2D collidable;
hahhaha
Just a thought dont laugh
a collision isnt something that just exists in the scene as an object
and if its public, marking it [SerializeField] wont change anything
If I am using an AssetReferenceGameObject to asynchronously instantiate a prefab with Addressables.InstantiateAsync, which returns a GameObject, what is the reason for calling Addressables.ReleaseInstance when done with the instance? I guess the question is why is it not correct to call Destroy on the instance? I would have thought it's then just another object in the scene.
is a box collider or raycast more reliable for detecting player jumps
Is there a way to check if a component reference is part of a prefab or part of an actual hierarchy object?
I got a weird issue with a outline package, where outlines are generated for all objects with a certain script - even in unopened prefabs
I think Addressables Team explained like this: We cannot know if an object destroyed. So the reference count would be stay the same or show wrong things. So in Addressables.ReleaseInstance() acts like an Destroy() here.
Or maybe i remember wrong. I will try to find that conversitation now.
Also, there is #📦┃addressables channel. There are more experienced users in that channel maybe looking sometimes
found a solution to my problem
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage && !prefabStage.IsPartOfPrefabContents(gameObject))
{
onRender -= OnRender;
return;
}
I hate this
Ref: https://forum.unity.com/threads/release-asset-vs-release-instance.540640/#post-3590593
And he also explains how the ref count works and what is the difference between instantiating objects in different way or using Addressables.Instantiate.
Ref: https://forum.unity.com/threads/release-asset-vs-release-instance.540640/#post-3589645
Good info, thanks! I'm not sure what their reference count is for in this case, but keeping it correct definitely makes sense.
I managed to not only make unity throw a missingReferenceException on a line
if (gameObject)
which is supposed to check exactly if it's a valid or non-valid reference
but on top of that, changing that to (this && gameObject) fixes the issue...
using UnityEngine;
using UnityEngine.UI;
public class AmmoScript : MonoBehaviour
{
public int maxRounds = 10;
public int maxBulletsPerRound = 6;
public Text ammoText;
[HideInInspector]
public int currentRounds;
[HideInInspector]
public int currentBullets;
private void Start()
{
currentRounds = maxRounds;
currentBullets = maxBulletsPerRound;
UpdateAmmoText();
}
public void UseBullet() // Bullet Usage
{
if (currentBullets > 0)
{
currentBullets--;
UpdateAmmoText();
}
}
public void Reload() // Reloading lol
{
if (currentRounds > 0 && currentBullets < maxBulletsPerRound)
{
int bulletsToReload = Mathf.Min(maxBulletsPerRound - currentBullets, currentRounds);
currentRounds -= 1;
currentBullets = maxBulletsPerRound;
UpdateAmmoText();
}
}
public bool CanShoot()
{
return currentRounds > 0;
}
public void UpdateAmmoText()
{
ammoText.text = "Ammo: " + currentRounds + " / " + currentBullets;
}
}
``` Can someone help me with this code? For some reason, the bullet count doesn't go to 0 when the round is 0.
look at the conditions you have in the methods that call the UpdateAmmoText method
I have this code currently that calls my constructor:
// Constructor
public TurnEffect(TurnEffectInfo turnEffectInfo) {
...
}
// Calls constructor
public TurnEffect(GameObject effect) : this(effect.GetComponent<TurnEffectInfo>()) {}
I want my constructor to have the following signature:
public TurnEffect(TurnEffectInfo turnEffectInfo, Battleable self) {
...
}
How can I change the "Calls constructor" constructor to work with this change? Thanks!
SOLVED
turns out i just need to put the type in the first part, like this :
Hello! I've been working on this script for a little while now and just wanted a little feedback on it, like any ways to shorten it or make it cleaner, sorry if there are any typos, I made this on my phone and probably mistyped a few things, but there aren't mistyped on the actual script, thank you if you do end up looking at it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have a list of names with a corresponding output. Some names are variations and point to the same output. Many people may need to add more names to the list over time. What are my options for doing this in a maintainable way?
I looked at enum flags, which seemed nice for the "get every name except this one" or comparing two names case, but needing to assign an int to each one seems fragile. People may add or remove names over time.
General suggestions or places to start?
a dictionary?
I'd do a dictionary with duplicates but I need it to be serialized or saved in some capacity
a dictionary is definitely the best solution for this problem. unity does not serialize dictionaries by default, but its possible to write your own serialization for dictionaries
so for example, make a "NameDictionarySaveData" class and make it implement this interface https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
in fact, the example on the documentation is literally a dictionary serializer
Ty I knew dictionaries weren't serialized by default but didn't realize serializing them was that easy
np 👍
i think the biggest way to tidy-up the code is to squeeze down all those nested if-statements
having a bunch of curly braces is the easiest way to make code harder to read, just because of how it spaces out all the important stuff
so for example in update i would do if(throwTimer >= 1f && Input.GetMouseButtonDown(0)) ...
instead of having them on separate lines
Okay, thank you! I will try to work on the amount/size of the if statements
np 👍
Why is Vector3.Distance of (5, 1, 1) and (1, 1, 1) equal to 4, but distance of (5, 2, 1) and (1, 1, 1) is 4.123106 ?
Shouldn't it be 5?
its not that simple
clearly
Because it’s further away. It might help to see it as a triangle, the hypotenuse is always the longest side
rotate the line in your head over the blue dot, it should be slightly longer than 4 units
Makes sense... i guess i will trust unity then
anyone have a problem with editorloop causing lag spikes in profiler?
It's recommended not to do serious profiling in the Editor for that reason
but isnt there some way to just disregard the editorloop stuff in the profiler
its lagging my game, when i debug.log fps its like 500 but when i look in profiler i have spikes often with it being under other in CPU and showing editorloop
as in its causing me problems playing my game in editor to check out stuff ive added
hmm nah i've never had the editor lag my game to that degree.. your pc isn't super old is it
its a laptop with 12700h and 3070, i have turned on dedicated GPU so it cant be running integrated graphics by mistake
could anyone who uses visual studio code recommend a good setup for writing c#? I have the unity roslyn analyzer package and omnisharp installed but omnisharp server is really slow. It takes a few seconds for code completion to kick in.
ditch the garbage text editor and use a proper IDE
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Normally I'd agree with you that vs is better for c# programming, but Unity handles all the asset management and compiling so I really just need an editor and a linter
The debugger is soooo important. That alone makes vs worth it over code
The "just works" part is pretty great too
I'll give it a try
Hello all, I am trying to resolve a problem that I am encountering when trying to make the player be able to damage enemies. I made a EnemyStats non monobehavior script so that I can make a list of that in 1. The problem, is that I need to reference the Hp of enemyStats in EnemyBehavior script. It says I cannot do that because enemyStats does not derive from monobehavior. Is there a better way to do this? Am I doing this the wrong way?
ping me please, thanks
1.script that gives all of the enemy prefabs an EnemyBehavior script via a list: https://gdl.space/pifeluwazu.cs
2.The EnemyBehavior Script: https://gdl.space/etiqetoguc.cs
3.The EnemyStats non monobehavior script: https://gdl.space/erodumadiv.cs
just ditch the "Unity Explorer" tab in vs and use solution explorer,my advice
create code files through vs, folders included
derive enemy stats from ScriptableObject
one object per enemy type
reference that SO in the enemy prefab directly
that is for edit time, immutable data
if you want to implement some sort of runtime abstraction for stats, it needs to be dynamically resolved/found on the enemy
the structure would be something like
GameObject
Enemy
references EnemyStats
EnemyStats
references EnemyStatsData, with initial stats values
contains:
class EnemyStat - created at runtime from EnemyStatsData
EnemyStatsData : ScriptableObject
contains initial float/int/bool stat values
gets converted to List<EnemyStat> at runtime
@rustic furnace
enum Stat
{
Health,
Armor
}
class EnemyStat
{
public Stat stat;
public float value;
}
class EnemyStatsData : ScriptableObject
{
float health;
float armor;
public List<EnemyStat> GetRuntimeStats()
{
List<EnemyStat> list = new List<EnemyStat>();
list.Add(new EnemyStat(Stat.Health, health);
list.Add(new EnemyStat(Stat.Armor, armor);
}
}
class EnemyStats : MonoBehaviour
{
[SerializeField] EnemyStatsData _data;
Dictionary<Stat, EnemyStat> _stats;
void Awake()
{
var list = _data.GetRuntimeStats();
foreach(var s in list)
_stats.Add(s.Stat, s);
}
public EnemyStat GetStat(Stat stat) => _stats[stat];
}
woah, thank you, I will study this
I def need to learn more about this because I didn't understand most of it
Is there a way to customize the element names in serialized arrays like this one using editor code or another way. I want to make it an abbreviation of the element it so I can see it at a glance.
any first string of the class
unity will use first string in the class as a "name"
I see, is there another way that just overrides the gui draw of the editor. It's a struct the represents a crafting recipe so I'd like it to be lightweight.
a string is a 8byte reference
Ok ok it's just a preference of mine
alternative is property drawer
i have no idea if it will work in array
as arrays are drawn by unity in a very specific way
public List<EnemyStat> GetRuntimeStats()
{
List<EnemyStat> list = new List<EnemyStat>();
list.Add(new EnemyStat(Stat.Health, health);
list.Add(new EnemyStat(Stat.Armor, armor);
}
Is this returning a new List<EnemyStat>?
should yes, but i forgot'
I see, I'll look into property drawers. Thank you 👍
solutions to this vary wildly
i really suggest just to use a string
one good thing about it is that you only need it in editor
so you can if it
What does the last line do? I'm not sure I understand it fully.
#if UNITY_EDITOR
[SerializeField, HideInInspector] string DEBUG_NAME;
#endif
im not sure how serializer will handle it, should be no issues
public EnemyStat GetStat(Stat stat) => _stats[stat];
?
yes
returns the relevant stat object, by the enum value from a dictionary
this is in essense how you reference the stats at runtime
you grab the relevant runtime stat instance
make sense
im trying
I'm trying to understand how I could implement this
Alright, I'll do that soon
then what would I need to do? Can you give me a step by step
i have a feeling you might be interested in two concepts called "manhattan distance" and "chessboard distance." euclidian distance is the straight line (thats what unity uses in Vector3.Distance) but there are other types of distances that are more useful in different scenarios
Hmm I will look those up, thanks
https://docs.lunalabs.io/
any one have try Luna Labs to make playable ads? Which way do you prefer? Build the project from start or convert it from current project?
Luna Labs Developer - Docs
This code makes my game go from 140fps to 40fps on a 4090 and it's drawing a few lines... I assume I'm doing something wrong? lol
I mean I could probably make the lines a lot longer instead of drawing squares, that'd make more sense but still... it shouldn't be that expensive?
Okay... so rewriting it fixed it, it turns out that it is expensive to do a lot of lines 
Does the same thing but costs less than 1fps instead of 100fps lol
Turns out my chunks were turned up too high too... meant to be 3x3 but was 9x9 and drawing 44,100 tiles so... guess that's why the lines added up
How do I send a message to a client from a c# server
Guys tell me a good question to ask to discord bot
what discord bot. does this have anything to do with Unity?
Hello,
I want to Instantiate a 3D Model in my UI but it doesn't get shown. I have my camera set to only show the UI layer and after I Instantiate the 3D Model I also set the layer of the GameObject to the UI layer. When I play and Instantiate the 3D Object, in my Scene view the 3D Object gets displayed in the right position but the UI Camera doesn't show anything there.
How do I fix this?
Here in my Method to Instantiate it:
{
Transform parent = characterMenuUIParent.transform.transform.Find("Character Model Container");
for (int i = 0; i < parent.childCount; i++)
{
Destroy(parent.GetChild(i).gameObject);
}
GameObject characterModel = Instantiate(selectedCharacter.CharacterModel, parent);
characterModel.transform.SetParent(parent);
characterModel.layer = LayerMask.NameToLayer("UI");
characterModel.transform.localPosition = new Vector3(0f, -350f, -45f);
characterModel.transform.eulerAngles = new Vector3(0f, 180f, 0f);
characterModel.transform.localScale = new Vector3(370f, 370f, 370f);
}```
My Editor is stuck on this, how do I stop this without having to restart my editor since I didnt save progress 😭
Wait nvm it crashed now
was this when you pressed play?
When I double clicked an error
But it was an editor if I am right
Ah weird, probably not much you couldve done once it started
Your mesh looks properly positioned but is it actually in the camera frustrum ?
It works fine with the exact same properties if I just place the gameobject before I start the game. It only is like this when Instantiating the object.
you should change the layer for the children objects of your gameobject too
I didn't notice before, but the object you're moving into UI layer is only the holder, but it doesn't move the actual mesh (which is its child) in the right layer
@ancient crag
Oh, thanks. I completely forgot to change the layer of the children
Ye, it works now. Thank you
Great ! 🙂
new int[] { 0, 1, 2, 0, 2, 3 }
What does this do?
An array of 6 ints that contains 0, 1, 2, 0, 2 and 3
Are you by any chance coding with chatGPT @proper flume ?
OK
but
whats the {} for
cant you just do
new int [0,1,2,0,2,3]
It's not, but this part was in your code yesterday and it's weird you don't understand your own code haha
[] is for the size of your array
{} is to initialize the content
well
This video explains how to use arrays to collect variables together into a more manageable form!
Learn more: https://on.unity.com/3ggq3Ov
then how am i supposed to pass multiple triangles to mesh.triangles
but if you do new int[]{0,1,2} you initialize it with 3 elements
I have a road that is circular and is divided into three lanes, kinda. So, I need to instantiate different objects on that road which fall under 3 different categories names Gates, Obstacles and Coins. How do I approach this in such a way that the spawning would kind of look organic? Like, I don't want objects spawning on top of each other, I don't want too many obstacles spawning in one area that it makes it impossible to navigate through that area without getting hit etc.
I just need ideas, dww I don't need scripts, I will try to figure it on my own :D
with an array, as it takes multiple elemnts
mesh.triangles is an array of int, that is used to interpret triangles. triangles are actually a group of 3 ids (0,1,2 or 0,2,3 in your case).
Yes, because a square is 2 triangles
it will create 3 triangles?
Yep
Doesn't your tutorial explains it ?
unpack a array and add the values to another array
because im accepting it as a parameter
I could link you an intro to mesh generation if you lack the fundamentals
for a function
and i want to add them to another array
oh wait fuck.. i forgot you cant
Well
Is it to happend to the array or override ?
sry, english is not my main language, i can make spelling mistake ^^'
Maybe the person from the video make a new array that contains both the old and the one passed as parameter
hard to say without seeing the actual tutorial
i have issue with One or more cyclic dependencies detected between assemblies
what people do to go around it ?
Do you know how the numbers work
I dont know how to make another square
The numbers ? In the triangles array ?
Well
each number in a triangle array is an index of a vertex in vertices array
It doesnt show any position its just pure numbers and i dont understand it
ohh
Read this
Explaining it would take time, but this should cover the basic of mesh generation
fuck this is getting complex
But as Geeko said, numbers in triangles array are indices of vertices contained in the vertices array
Well, mesh generation requires a basic understanding of how things are rendered haha
This aint Roblox, this is big people game development
If you're more of a video person than a reading person, look at this https://www.youtube.com/watch?v=ucuOVL7c5Hw&list=PL5KbKbJ6Gf9-d303Lk8TGKCW-t5JsBdtB
Learn the basics of making a custom 3D object with code in Unity -- also known as a procedural mesh. In this video we do a quick review of what information is required for a simple mesh to take shape.
Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Check out Board To Bits on Facebook: http://www.facebook.com/BoardToBits
largest ? you mean last ?
yes
well, last index should be array.Length - 1
because index starts at 0
you could also do [^1]
why cant i do array.length
yes, but for the triangles, it won't work
ah right
for some reason im a idiot and changed it to a list
actually thats gonna make stuff easier
does list.count require a -1 too
yep
ok
how to check if a list has 2 the same values
what do you mean, ^x is just a "from end" instead of "from start"
can you pass it as a vertice index in the triangle array ?
hello i need help integrating unity with vscode
all i really saw was getting the last element of the array, not entirely sure what you mean here
like
list [Vector2(0,0),Vector2(0,1),Vector2(0,0)
so then it detects there are 2 Vector2(0,0) so i can delete it
one of them
The context is building mesh triangles. And I suppose they want to get last index of vertices array to pass it in the triangles array
array.length - 1 is the same as ^1
com on
oh wait
im stupid
Yeah I know, but I genuinely don't know if it works outside of []
idk maybe im missing some context then, i assumed you were gonna do [array.length - 1] from the beginning
like if you do triangles = new int[]{0,1,^1} does it store it properly ?
^1 is an index, so no you cant store it in an int array. I just saw that they wanted to get the last element so like
var triangles = new int[]{0, 1 , 2};
var val = triangles[^1];
would be grab the last. Im unsure what you're referring to now because idk why its being stored
Well that's why I'm using Length - 1. they're doing mesh generation. They have an array of vertices. to build triangles, you have to store vertices index in a certain order
Meaning at some point you'll use the last vertex, which I suppose they wanted to access
Hover over it and read
and please use full sentences, I see you've been posting quite spammy
cannot convert from UnityEngine.Vector3 to System.Predicate<UnityEngine>.Vector3
well you cant use the length of the collection before its declared either, so I really am confused what you mean. But its ok i just assume im missing context on something
Where did i spam
#archived-code-general message everything you post covers multiple lines for no reason. Use full sentences.
Ok
You probably want Contains and not Find.
2 arrays: vertices and triangles, vertices stores vector3, the second stores indices of the 1st one. so it should be vertices.Length - 1 stored in triangles. obviously vertices needs to be declared first.
It worked thank you
Ah i get what you mean, my misunderstanding. The only mesh stuff I did was pretty different then
Thank you guys i figured it out
Well played 🙂
No you can't
Why do the unity devs need to make this so much more complex
You'll always have to build triangles from vertices indices
It's not Unity, it's how rendering works in general xD
Actually, in comparison of some other 3D library, it's pretty easy the way you can do it with Unity
Im getting lots of issues now because when i generate the terrain vertices I will need to add vertices below existing ones in order to achieve a blocky terrain
But then they will have messed up indexes
Look up what Linq is and get used to filtering collections using it
For this particular question you also have solutions, like Distinct, Intersect and some other methods
Intersect is what you want specifically for this case https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.intersect?view=net-7.0 see examples
Just know that c# comparison is failrly basic so you might want to indicate what exactly must be compares for them to be "the same thing"
Is there anything important at all in EditorUserSettings.asset, or can I safely add it to gitignore?
It KEEPS causing conflicts and while it's 2 clicks to resolve, it's happening so often it's driving me crazy
If you are using the official gitignore for Unity then you would have ignored everything that there is to ignore.
I'm using it, but that doesn't answer my question
This file keeps being randomly edited by unity for no reason at all, but unlike OpenXRPackageSettings.asset (which also keeps being changed allll thee timee) which can have important things in it, I'm not sure if EditorUserSettings.asset does
https://forum.unity.com/threads/whats-the-usersettings-directory.754436/
The folder should not be put into version control, since it's per-user things there.
I guess I found my answer
(was the old way)
that's not applicable anymore?
When making a hardcoded (no rigid body) 2D Character controller, what is the least performance heavy way of ensuring the player does not glitch into the floor/ceiling/walls. I've tried ray casts but they are relatively performance heavy and have a few inconsistencies. The glitch into the level is because I am using Fixed Update and in the frame of reaching the ground it moves enough to go properly inside the ground, so setting velocity to 0 when touching the ground does not work.
raycasts aren't that heavy. If you're concerned, you could use something like boxcast, which I believe works kind-of like a collider, but it's probably similar to a raycast in terms of preformance
raycasts are heavy when you go into thousands per frame
before that I think you're fine
Well not performance wise but has a few inconstancies which are very minor but exist, for instance you would be able to glitch into a wall if you jump perfectly into the corner
boxcast is your solution then!
or spherecast or whatever else of that type
could be solved by changing logic too, but box casts are probably far more reliable
or just do 2 raycasts per directionl, one at each end of the character - but I suppose boxcast does that but better
problem with that is you can glitch into the ground if jumping on a tile thinner than your character
ill try out box colliders, thx
Hey,
How do I get the specific UI Element I started dragging with the IBeginDragHandler Interface? It only detects the canvas but not the GameObjects/Transforms inside of the canvas. Is there a way to check if I started dragging a specific GameObject or Transform inside of the canvas?
This is how I have implemented the check right now.
if (eventData.pointerDrag.transform == characterModelParent) isDraggingCharacterModel = true;
Only RectTransforms can be dragged like this I believe.
But what I'm trying to drag is a RectTransform
you need
rect transform
:graphics component
: enabled raycast target
:script that implements IBeginDragHandler
Maybe you are missing one of these? Probably the graphic usually.
NOTE: you can just inherit Graphic in your script too.
I can't find the graphics component
And if you mean the Graphic Raycaster, it doesn't work as well. The only object it hits is the Canvas itself but not its children
does the child you want to move have a graphic component, such as an image?
The objects that you're dragging should have the components with the IBeginDragHandler interface
you need to have one in order to make it clickable
You don't put it on the canvas or something, you put it on the objects you actually want to drag
and to get what you're dragging? Well, it's this
No, it's just a parent object for a 3d Model.
having a 3d model as a child of a canvas doesnt look so good..
maybe you want to think about it, like having a script to move it in world space
or maybe having a camera recording it in world space and a RawTexture showing it in the canvas
I currently have an extra light just for the 3d model in the canvas. It looks fine that way
It may look fine, but it's not recommended to add non-ui elements to canvas
it can lead to a lot of problems
Okay, thank you. I'll try it the other way then. It's my first time using non ui elements in a ui.
A quick guide to using a render texture to show a 3d object in your UI. This is a real-time object you can light, rotate, scale, etc as needed.
In the video I'm using a pirate ship from Synty Studios - Polygon Pirates.
Leave a comment below and let me know what you think and any content you'd love to see in future videos.
Grab yourself some ...
Thank you. I appreciate it.
this may help, I'm not really sure what you want to do, but this is one way to show a 3d model inside a canvas
My model now gets shown in the Canvas but it is see-through when it gets rotated. In the Camera view it gets shown as normal though.
can you do a screen recording showing the issue and also showing a little of how your camera is positioned, please?
ok, i see it
a question for you, does all the children of your model have the same layer as their parent?
UICharacterModel
Is there a reason you have 2 character models in your hierarchy ?
One is for the UI and one for the player to move in the world. I want the model to be shown and rotated in a menu
it looks like something is in the ui causing this visual issue
have you deleted the 3d model in the canvas already?
Did you change the layer from the model that is in the scene (that is supposed to be in game) ? you set it up as UI this morning
yes
The one which was in the UI is deleted and the other one has the Default layer
make sure the other model that you dont want to be shown does not have the same layer as the ui one
It just looks like one is overlapping with the other
They are not on the same layer
Even children ?
No, the one in the RAW Image is on the "UICharacterModel" Layer including children and the other one is on the "Default" Layer including its children
OK.
Did you check your camera clearing settings ? I suppose so, but sometimes we can forget
Do you mean the Culling Mask?
Yes, it should be set up properly
But one camera is rendering both characters
But how does it even happen? My other Cameras are not showing that layer and the other model is at a completely different location
Try disabling Character Model Image to see if it's related to the render texture
Because it looks like something is going through it
And the preview looks fine, so it's shouldn't be a rendering problem on this side
When I disable the image it works as inteded. Doesn't get shown anymore and nothing but the blue backgrounf behind
Now that's weird
I don't think so, you're just feeding it what the camera renders
And you checked the camera with preview
Try disabling the character to see if the render texture display anything else
It's not showing anything when the model is disabled
This behavior is puzzling
There's no reason for an arm to appear there
Wait a minute. What's your canvas setting ?
My Render Mode?
yep
Screen Space - Camera
Set to main camera I suppose ?
Move the Canvas camera away from the character
To my UI camera
which only shows the UI Layer
oh, that may be a problem
The Raw Image is on the UI Layer though
Is there a built in function to say how much distance of a raycast intersects with a specific layer. I know the .distance function for 2d raycasts returns the distance till it reaches that specific collision, and that could be implemented to make a function like described, but just checking if there isn't an easier way
Not if it's for modding/cheating.
if you have the source position, you can calculate the distance using hit.position
since they're both vectors
So for instance if i had 10 randomly arranged blocks of 0.1 length, and a random 4 of these blocks where with my specific layer, if the raycast went through all at the same rotation angle, it would return 0.4, for the 4 blocks it has gone through.
Still, the rules are clear: #📖┃code-of-conduct
DO NOT:
• Directly discuss modding or decompiling.
There isn't an exception for games that allow modding.
Sry, didn't understand your question that way. What i said won't help you
It was my render texture. I had to set the Depth Stencil Format to something else
Glad you figured it out
Sry, I wasn't of much help
The rule applies to the whole server.
you shouldn't ask anywhere on this discord
Regardless, everyone here is making their own games. Even those who have used Photon, will not have used it in the way you're trying to.
Ok, I'd like to learn it from the perspective of a developer.
If you know the "size" of your item, I suppose you could figure the distance if you get the amount of item crossed by the raycast, right ?
But you'd have to consider every scenario...
Neverming, I would have suggest RaycastAll to get the amount of item you go through but it won't be enough
Anyone know of a discord channel existing for developing for Quest 2 in Unity? this latest v56 firmware update has wrecked my app and need help figuring out what the heck they did
I don't think there's a built in method to do it, but this code example could help you https://stackoverflow.com/questions/26957613/unity-raycast-on-raycast-leave-how-to-c-sharp
They made a class to fire event when a raycast enter, stay or leave an object. You could extend to deduce the distance between entry and exit point
what I would do is:
For each hit collider:
- call Collider.Raycast (on that specific collider) using a ray in the exact opposite direction
- measure the distance between the initial hit and the opposite direction hit
I made a SO, now what do i do
should i start from layer 3 or layer 6 when adding my own layers? why is there a hole?
it doesn't matter. but this is also a code channel
one of those "Unity things"
Yeah wrighting up the script for it right now. Has some annoying behaviors but it is what is is
ok this is really frustrating... going to just ask here to see if anyone else is seeing this but right now Unity v2023 and Meta v56 firmware is an absolute mess when it comes to the microphone. sounds like a chipmunk having its voice interrupted every tenth of a second. only happens on device. in-editor is fine
if anyone has that combo working would greatly appreciate a DM so i can figure out what about my project is making it break
Layers 0-7 used to all be reserved by Unity, but they stopped using some of the layers, so they made those available to developers.
Is this how I should be doing game inputs?
if (SystemInfo.deviceType == DeviceType.Handheld)
{
// move based on joystick right/left with deadzone
if (joystick.Horizontal >= 0.3f)
{
movement = 1f;
//Debug.Log("Right");
}
else if (joystick.Horizontal <= -0.3f)
{
movement = -1f;
//Debug.Log("Left");
}
else
{
movement = 0f;
}
// if Joystick down, fall through platforms
if (joystick.Vertical <= -0.4f)
{
down = true;
//Debug.Log("down true");
}
else
{
down = false;
}
}
else
{
movement = Input.GetAxisRaw("Horizontal");
if (Input.GetKeyDown(KeyCode.W))
jump = true;
if (Input.GetKeyUp(KeyCode.W))
jump = false;
if (Input.GetKeyDown(KeyCode.S))
{
down = true;
//Debug.Log("Down");
}
if (Input.GetKeyUp(KeyCode.S))
down = false;
}
I have a question regarding how to use android phone sensor data in my game as explained here #📱┃mobile message
I would need your suggestions on how can I solve this issue.
why I cannot change cursor visibility until I clicked?
private void Hover(bool value)
{
if (button.interactable)
{
isHover = value;
Cursor.visible = !value;
}
}
is there any way I can simulate cursor click in code?
Guys how to i lerp a float value? Just the value not some transform.position or smt like that.. is there somethig like: intensity = new Mathf.Lerp(values) ??
thx
lerp returns float..
and takes 3 floats as parameters
so yes, you do lerp a float value, just float value
what did you do?
I'm working on a project with someone, and we're using github. Yesterday I created a couple new script folders and maybe 5 or 6 new scripts. I pulled his most recent commit, and it deleted all my new scripts and folders. I can't find them anywhere. So, A) any pointers on how I might recover them? And B) best practices so that this sort of thing does not happen again?
pulling your collaborator's changes shouldn't have deleted anything
at worst you would have gotten a merge conflict
1a. Did you commit your changes to a branch?
1b. If so, what was the branch name
2. What was the name of the branch you pulled your buddies changes on, and was it by chance the same name as 1b...?
unless they were both working on the same branch
at best you would have gotten a clean merge
even then you'd just get a merge conflict at worst
Yes, unfortunately.
or it would just say "can't pull changes due to local changes" or whatever
git does not delete stuff randomly
only for rebase/merge, if you force checkout the other persons commit it will completely wipe out all of your local commits
well if you force anything you're asking for trouble
I'm using the desktop version, and I indicated that I wanted to stash changes. But now I don't see those changes anywhere
if you had committed changes and then pulled your teammates changes and they merged and his wiped out yours then your code is still there in the commit history
oh
ah, those should still be stashed, you using github desktop specifically?
so you stashed them
then you just need to unstash them
idk how to do it in your desktop version
but the command would be git stash pop
Unless I clicked "Discard" by mistake, those scripts don't appear to be anywhere.
oh wait wait wait
are you looking at the right branch?
Yeah it's very hard to lose your work with git
I have only ever used github to back up my own work. Still learning the collaboration/multibranch aspect of it
If I were you
I would go ahead and commit your changes now
you don't have to push yet, but at least make a local commit
that's a lot more stable than the stash
I also heavily recommend both you and your buddy do work on your own seperate branches
and then when you have stable working changes, commit and merge your branch into main
and when you want to use your buddy's changes, you merge main into your own branch
^This is a good idea. It's also a good idea to periodically merge main into your feature branches if there are a lot of changes happening there, otherwise your branch can get kind of "stale".
i.e. you may end up with lots of annoying merge conflicts going back to main if you wait too long without merging main into your branch periodically
Then again I might be scarred at my day job where our main production branch gets like 100 commits per hour
Yeah, we definitely do not have enough discipline or procedure in place. Right now we just have one big project that has all of our scripts, many of which will conceivably be reused in future projects. At what point does it make sense to bundle up your prefabs/scripts into packages?
when you need em to be that way tbh, its not terribly hard to export out to a package, so no need to do it asap, I pretty much always wait until its actually 100% for sure needed before I package stuff up
Im trying to do a blinking effect with vignette but its all snappy and it doesnt lerp all the way
idk if this is correct or nah
why, is it somewhat of a pain to modify after it's packaged?
nah just no need to waste time on something you "might" need later for <future project> that has zero impact on <current project> atm
cuz you might blow all that time on it and never actually end up using it
also its hard to tell if you need just 1 big package, or if you want it divided up into a couple ones, etc etc
Well, current project and future project are sorta one and the same, in this context. This whole thing is going to be the handler for an escape room, and we'll use the same underlying guts for each of our experiences
So I wait til I hit that "oh man I really could use that stuff from my last project, we keep re-using it" point, then I package it up cuz now Im 100% sure I need it
Gotcha
the other thing is you may package it up, but then when you start the next project you actually have a bit of "If I was gonna do it all over, I now know there's a way better way to do it" and then the package you made is useless anyways XD
Let me give you a hint: Mathf.Lerp(1f, 0.4f, 0.5f) is EXACTLY IDENTICAL to just writing 0.7f
may i know why?
Mathf.Lerp just returns a float
Mathf.Lerp(1f, 0.4f, 0.5f) means "give me the value halfway between 1 and 0.4"
it's not a magic function that goes off and does things over time
it's just a math formula that takes in a few numbers, and returns a number
actually speaking of, is there some kind of utility function that actually can do that, cuz thatd be nice
Yes DOTWeen
or any tween library of your choice
but DoTween is the best tweening library for Unity imo
does it support IEnumerators?
so the "t" value is basically the number that you are gonna divide to?
you can make a coroutine wait for a tween, yes
for Lerp(A, B, t) t is the portion from a to b
if you pass in 1 you'll get B
If you pass in 0 you'll get A
pass in .7 you'll get 70% of the way from a to b
i tought it was to control the speed or smt
Im almost imagining a "lerping" interface for a couple common structs (float, vectors, etc), lets call em Lerpers, that are "bound" to a local member.
And then a Lerp IEnumerator for time, that takes an array of "lerpers" and a time value
you thought incorrectly. It is often improperly used that way but even when it's used that way the work of "doing it over time" is happening because it's runnning repeatedly in Update for example
is there a way to select all uses of a variable and change the name on all of them
yes your IDE should let you right click the variable and rename it
oohhh, but what about the snapping thing?
it's snapping because you are waiting 1 second and then setting to a new value instantly in your coroutine
but im doing a blinking effect so it shouldnt be like tht?
you're trying to do a blinking effect but the code you wrote is the code you wrote
good point
but to control the speed it should be like: vignette.smoothness.value = Mathf.Lerp(1f, 0.13f, 0f) * speedValue; ?
no
there's nothing to control the speed of
Mathf.Lerp(1f, 0.13f, 0f) is equivalent to 1
if you want to do things over time you need to write code that is going to change the value a little bit every frame over many frames
agaoin Lerp is just a simple math function
This is literally the definition of Lerp:
public static float Lerp(float a, float b, float t)
{
return a + (b - a) * Clamp01(t);
}```
just some very simple arithmetic and clamping t to [0, 1]
of course you can control the speed
who said you couldn't
it will only take as long as you want it to take
in the code example you showed
oh
if you wrote code that was actually changing things over time, there would be
what do you mean by this statement, perchance?
hey i need some help, in a general sense how would you begin to make a code for mashing a button
doing the opening thing frame by frame yk
kinda moving the position every frame with code
What makes you think it will "take a long time"
do you mean it will take a long time to run, or do you mean take a long time to physically write the code
physically write the code
You can use a loop to make it quite simple, I think only 4? 5? lines total?
I recommend DOTween
this should make it lerp to the 0.4f value right?
it will make it much easier
bruh
it will immediately set it to 0.4
how many times do I have to say that Lerp is just a simple math formula lol
you're not seeming to understand this
i am not 💀
like a for() loop?
Hint: you prolly want something roughly like this:
while (vignette isnt done blinking) {
var timePassed = Time.deltaTime;
vignette.intensity.value = Mathf.Lerp(....);
yield return null;
}
(further hint: You prolly need to use timePassed variable inside of Mathf.Lerp)
yield return null basically just means "WaitForFrames(1)"
woops
that’s the same thing as
vignette.intensity.value = 1 + (.4f - 1) * 1;```
float duration = 1f; // time in seconds the interpolation will take
float timePassed = 0;
while (timePassed < duration) {
timePassed += Time.deltaTime;
float t = timePassed / duration;
intensity = Mathf.Lerp(startintensity, endintensity, t);
yield return null;
}```
So see how we're using the elapsed time to create the "t" value?
Lerp is not making anything happen over time. It's happening over time because we are doing a loop with `yield return null;` (which waits one frame) in it
stand by please i need to process
Hello! Quick question: Can someone give me a reference/link to documentation that indicates how I would go about making a package I created be imported into the Packages folder instead of the Assets/root folder?
hey can i get help, i'm not understanding how to make logic behind mashing a button script
im gonna try this
this is ok except you're only changing this intensity variable which isn't going to affect the actual vignette
that's kinda my bad I guess
OOOOHH WAIT
it should be vignette.intensity.value = Mathf.Lerp...
Is there any way to force enter a game? Cursor class doesn't work until I click on smth inside my game.
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
In the editor even if the cursor is locked it won't actually be locked unless you give focus to the game window
this is so you can still do editor things while the cursor is locked
thanks.... i just need help on how to make a simple button mashing script
yes, is there a way to focus on the game window when the game is started?
I think the game window might have a dorpdown option?
Play Focused / Play Unfocused
idk man i cant understand this shi
which part is confusing you
go over it line by line
the t value
and tell me when you get confused
t is calculated as float t = timePassed / duration
it's just the percentage of the way through the animation we are
if duration is 10, and timePassed is 3
t will be 0.3
I play focused, it doesn't focuse though
make sense?
I'm all out of ideas then
I see, thank you for your time 😄
can i change the timepassed value?
why
time passed is representing the actual amount of time that has passed
we wouldn't want to change it from that
idk man, im trying to understand
we are changing it every frame with timePassed += Time.deltaTime;
this way it always represents the amount of time that has passed since we started the process
which is what we want it to be
duration is the duration
like the length
wait
button mashing script? what's that even mean
Maybe explain what a "button mashing script" is supposed to do?
wait i just got a little help from chatgpt here, so lerp is a function that the t float value clamps it based on a fraction of it?
like this?
i cant represent too much
that is what i said
here's another good resource about how lerp works with a handy slider to see what the t value does
https://unity.huh.how/programming/specifics/lerp/overview
i didn't really understand "he t float value clamps it based on a fraction of it" but if it means the same as what I said then sure
yeah i cant say what i think and see that much
when the player falls into quicksand and, they get stuck i want a script to where when you mash jump(spacebar) you can get out
so like if the player mashes under a certain amount of seconds they can get out
wait so the t is the percentage?
man
yes, t is the percentage from a to b, but unless you are using LerpUnclamped then t will be clamped from 0 to 1 so it cannot go beyond or below a or b
thank you guys
yep
float height = 5f;
float sinkSpeed = 1f;
float mashAmount = 0.2f;
void Update() {
height -= Time.deltaTime * sinkSpeed; // always sinking
if (Input.GetButtonDown(KeyCode.Space)) {
height += mashAmount; // mash the key to go up
}
if (height <= 0) {
print("You died!");
enabled = false;
}
if (height >= 5) {
print("You lived!");
enabled = false;
}
}```
Something like this?
yea okay i see, yea something like that
so my code works perfectly...I switch scenes, come back and now it breaks...am I missing something obvious?
anytime heroshowing is set it should debug
probably due to some static variables or non serialized state on your scripts?
it prints the debug here
then the code is ran here....
and the heroshowing is now different....
its now Aizen even though no where in code it should change and even the debug shows it doesn't change
non serialized state?
yes, any variable that isn't serialized
it will go away on a domain reload, but if you don't have domain reloads enabled for entering playmode it can stay unexpectedly
it's also unclear what the scope of this heroShowing variable is
no
but where is this HeroInfo from the button coming from?
hmmmm
this is inside of start
GameManager.instance.playerInventory.ResourceAmtChanged += () => AddMatsToInventory();
GameManager.instance.playerInventory.HeroStatsChanged += () => AddMatsToInventory();
GameManager.instance.playerInventory.HeroStatsChanged += () => UpdateHeroInfos();
I probably needed to remove these when script was destroyed first time?
or when script is destroyed should these be destroyed also?
bunch of info thats initialized when script is started
this looks like some stuff that needs to be unsubscribed
is GameManager a DDOL singleton?
yeah
yeah... this isn't going to fly
especially since you're using those anonymous lambdas - you won't be able to unsibscribe them properly
rewrite like this:
GameManager.instance.playerInventory.ResourceAmtChanged += AddMatsToInventory;
then unsub in OnDestroy:
GameManager.instance.playerInventory.ResourceAmtChanged -= AddMatsToInventory;
I have no idea if this is your current issue
so because I used the anonymous lambdas I wouldn't be able to unsub them the other way?
but this is definitely an issue
yes because they're anonymous you don't have a reference to them to unsub with
would be shocked if it was the issue since Im debugging anytime the variable should be set and it never debugs again before its called and has wrong value
appreciate the fix reguardless 😄
everything works correctly first time, I then go into another scene, come back and then the issues happen
welp
I'll try again but unsubscribing those fixed it
yeah that fixed it thanks! not entirely sure how that caused the issue but it works now 😄
how I've just got to figure out why if I doubleclick super fast it breaks something else when clicking regular speed it works fine when popping up first item lol
oh the fun of debugging
hello I am trying to make the enemy rotate until the weapon be aiming at the player but I have no idea how to make it can someone help me making it ? https://cdn.discordapp.com/attachments/885300730104250418/1139523817434251284/2023-08-11_14-36-40.mp4
looks like issue with your avatar mostly
eg animation for shooting root pos /rotation not matching the one for idle or w/e
does this matter for sub/unsubbing if its not part of a DDOL? If I should still unsub it do I need to just store this as a variable?
BackgroundButton.clicked += () => StartCoroutine(buttonClicked());
I would always put my event subscriptions in their own Method wrappers, it makes it 100% ensured you can sub/unsub correctly
Im not entirely sure what that means...could you give me an example?
just your typical void MyMethod(theEventParams)
so in your case
private void OnClicked() => StartCoroutine(OnClickedRoutine());
and then you can -= / += OnClicked
oh I didn't think of this I will try it
I will be back in a minute to see if I can make sense of this and respond...wife at store and forgot her wallet lol
Its just typically safer to always have the "top" level of your event subscriber method be an actual concrete method, not an anonymous lambda
if you need to unsubscribe at least. I try and avoid ever having event subscribers that can be destroyed/disposed of in the first place, then you dont even need to worry about it
thanks man it actually work ur a g
if the lifecycle of the BackgroundButton is less than or equal to the lifecycle of the script that is listening, you don't need to unsubscribe
Is if possible to do this kind of shadow in unity?
there is a shadow around this panel
aka if the left side before the += is destroyed at the same time or before the right side I dont need to unsub
GameManager.instance.playerInventory.HeroStatsChanged += () => UpdateHeroInfos();```
so when it was this before....the right side script was destroyed before the left side so I need to unsub it
that makes sense thanks
would just need a list of the params from the method to pass back into the unsub method then 🙂
so theres a scrollbar component right, the value is in decimals, i need it in whole numbers based on what step its on, so if its on step 1 the value is one etc how could i do that
i just realized theres something called a slider
that seems to fit what i need better
yup that works way better
right
exactly
awesome thanks!
I will have a look on this, thanks
Is there ever a reason to use System.Single instead of float? Like, ever in any case?
yes i know but I'm just wondering because I see some things in the unity documentation and c# documentation say they return System.Single not foat.
i mean, if you know that they are literally the same exact thing then why are you confused?
float is System.Single
just like string is System.String and int is System.Int32
yes but I'm wondering why they say System.Single and not float, when in other cases they say float
it just seems like an odd choice and I was wondering why they would do that, maybe there's an actual reason I'm not aware of, etc.
it's the same thing
that's like asking why someone would type out the full "boxfriend" when addressing me when "box" would do just fine.
there is no difference except in the number of characters typed
Probably because inside C# it's actually called System.Single and they used some automatic tool to generate the documentation which spit out System.Single
float is just a convenient alias for System.Single that the C# language respects to improve the experience of developers who transitioned to and from other programming languages, since float is used in many, many languages
e.g. if you do Debug.Log(5.5f.GetType().Name) you will see System.Single
thank you for the explenation. The automatic tool thing makes sense.
Why there is not PreUpdate like LateUpdate. It is useful really in some situations
I hate to use execution order
You could definitely implement that pretty easily and just only change the execution order on 1 script. All other scripts just add itself to some delegate chain
I'm trying to write a Unity playmode test, but I need it to run in different scene (not the autogenerated one). How can I do that? Switching to the scene directly leaves my test pending and throws exception somewhere in OnPlayModeStateChanged
(there is an error when assigning the workplace because there is no workplace in the scene)
is this dots? might wanna look at the #1062393052863414313 if so
all i can see is that your coroutine never yields in this code
I want to load entries as Object and then cast to specific type in a library script
why
I would honestly make a custom class holding both the object and its type but i'm no professional so there might be better ways
yeah a generic class sounds better than just dumping everything into a single list as Object
i mean, yeah. that's called downcasting. but why should you have to do that, when you can just, you know, not
you're basically trying to circumvent c#'s type safety by storing everything in a big ol list regardless of whether they should be together or not.
what happened to "I want to keep this code as clean and straightforward as possible"?
then why do you need to store them in a List<Object>
here this might help you explain wtf you are trying to actually do: https://xyproblem.info/
fine, then have fun with your convoluted code where you have to type check and cast constantly 🤷♂️
i won't help you try to find a cleaner and better solution if you're just going to be a dick about it
and your simple question is very likely a bad way to do whatever the fuck it is you're attempting. of course you won't actually say what you are attempting because you are so adamant on going through with your bad solution so a proper solution cannot be suggested
hence the XY problem: #archived-code-general message
this channel is becoming steamy hot very quickly
how many distinct types do you actually need to load
only 5? Then I would make a wrapper class for each type instead of doing casting, as "is a" checks are fairly costly and perform very poorly, pretty much always a big code smell, very difficult to maintain, etc etc
What are you doing with these asset objects after you cast them?
So do you have some kind of switch statement on Type happening somewhere, and then you do a cast to its concrete type inside the different options
And you have distinct unique logic for each of the 5 types, largely speaking?
what method are you using to load them?
Like are you just calling Resource(s).Load()?
I see.
LoadAll() has a hard typed via generic overload, use that
What do you wanna do with the _loaded in the end? Like you just got 5 distinct dictionaries you wanna fill up with their respective assets?
right but just to confirm, do you wanna end up with effectively 5 seperate dictionaries, 1 per type?
Like
Library.Sprites, Library.Materials etc?
Perfect!
Use Generics.
but Pixxel, they just wanted to cast and it was a simple question and they just wanted an answer for just their simple question. they know what they are trying to do and their approach
public class AssetLibrary<T> {
public AssetLibrary(string folder) {
_folder = folder;
}
private string _folder;
private Dictionary<Id, T> _assets { get;} = new();
protected async Task NextIndexAsync(Index index) {
...
var _loaded = Resources.LoadAll<T>(folder).ToList();
foreach (var entry in _loaded) {
_assets.Add(...);
}
}
}
Something vaguely like that like that
because its extremely expensive and will be very difficult to maintain
Its a lot like if you took a box of spaghetti pasta, ground it up into powder, hydrated that powder, formed it back into spaghetti noodles, and then cooked those.
Like yeah sure I guess it works... but why didnt you just cook the spaghetti you had in step 1?
I dunno it would just do whatever you need it to do, but in a type safe way
And then yeah your "parent" object would just have 5 instances of AssetLibrary which is what you wanna end up with anywho
I just copied your method's name, you would make it do whatever it is you are hoping it will do :p
you cast a foo to a Bar simply via (Bar)someFoo
what error are you getting?
Texture2D contains a ref to a sprite, but is not the sprite itself, prolly what caused that
My motto is "do it right, or you'll just have to do it again"
So I finished my player movement script and I was moving
But then I finish my MouseLook Script
and I can move mouse but not player
Hey guys! I'm using the Unity Terrain object and while my character interacts fine with level ground, if I attempt to make hills of any kind my character collides with them and proceeds to clip under the level. Is there any way to fix this?
I'm trying to use a non-MonoBehavior class, and it's setting itself to null every time that the code recompiles during runtime.
Is this an error I'm making, a workflow that Unity doesn't support, or a bug that I somehow can't find on google?
This behavior can be recreated with the following steps:
- create an empty 3d project in 2022.3.1f1
- delete all objects in scene
- create a new empty object
- attach the script,
Foo.csto the empty object
using UnityEngine;
public class Foo : MonoBehaviour
{
private Bar _bar;
void Start() { _bar = new Bar(); }
void Update() { Debug.Log(_bar); }
}
public class Bar
{
public Bar() { }
}
- press play in Unity editor
- console should be logging
Barevery update, showing that the private instance variable_barto hold an instance of the objectFoo - edit
Foo.csby adding white space to the end of a line, and save the file to force a recompile - console should now be logging
Nullevery update, showing that recompiling has set the private instance variable_bartoNull
This has been baffling me for months before I thought to ask for help here, so thanks in advance for providing some form of closure to this!
I dont think recompiling while playing has ever been good. You shouldnt really rely on it to do what you want
i dont fully know why its even an option honestly
when you do the recompile during runtime any non-serialized field will be reset to default
Since Bar is not [Serializable] nor is the field serialized, it will not be preserved
that feature sucks though
but it will be "fixed" if you do this:
public class Foo : MonoBehaviour
{
[SerializeField]
private Bar _bar;
void Start() { _bar = new Bar(); }
void Update() { Debug.Log(_bar); }
}
[Serializable]
public class Bar
{
public Bar() { }
}```
(also Start will become redundant since Unity serialization doesn't allow nulls anyway)
completely confused why do you assume Bar should be null on recompile
it will be assigned in Start at runtime
@lean sail @leaden ice Thanks! That's really good to know! I thought I was doing something really stupid that was creating the error for months until I spent today minimizing down to the example project above in an attempt to solve it. It's nice to know that this is mostly just something that everybody lives with, and even better to know that there is a way around it if I feel I really need it! Although serializing all of those fields just to support recompiling during development seems like more effort than its worth in a larger project.
If you reproduce the steps I listed above, it will be null. I was confused too.
lets just take this and break it down
public class Foo : MonoBehaviour
{
private Bar _bar;
void Start() { _bar = new Bar(); }
}
_bar will be null in editor, guaranteed
after your run it, if the scene reload is disabled, it may retain the value of the _bar from Start in editor
at runtime no matter what you did in editor the Start will be called and _bar will not be null
I simply turn off the "recompile during play mode" feature in every project I work on.
yep, there is no sane way to retain the ability to hot reload
maybe you can have some isolated environment specifically for developing very barebones scripts that will support it
Did not know this was a feature, disabled it now, thank you so much.
so what i missed was that you were recompiling while the game was running?
makes sense, since Start will not be called after compilation, but the whole domain will be dropped
meaning any non serialized values will be lost
I'm having a dillemma, should I learn Cpp or C#?
Yeah, not intentionally or anything, but while trying to debug this was happening to me constantly, causing me to lose the log, and forcing me to stop and restart the game manually, then reproduce the bug.
Do you want to use unity?
if you dont understand what is domain reload, you should read up on it to understand the implications, and why it happened to you
Will do, thank you!
Yeah I do want to use Unity but I also want to prepare for jobs in the future.
Cpp is highly regarded iirc.
this is offtopic, but nothing stops you from learning both
with preference given to c++
Whatever you end up focusing on first depends on your goals
as a lower level language with direct memory management you will generally understand computers and programming better, with c# while being similar in syntax and structure, it is a language that runs on a virtual machine, that takes memory management and many other things out of your control
Yeah I can learn both but it is better to give my full attention to one thing so I can master that one thing.
.NET c# jobs do exist
Yeah.
yes there are jobs for any language, however those jobs will rarely include engines, servers
Yeah, I am really fascinated by the engines bit.
and servers.
Soo probably CPP right?
you really want to make your life decisions based random people on internet ? lol
what do you think looks more comfortable / easy for you to pick up on ?
learn whats more comfortable for your learning
you probably wont have a great time learning c++ if you severely struggle with c#. And tbh most jobs wont even consider you for these roles if you dont have a degree.
so I wouldnt consider learning a language in terms of which job itll get you
Honestly, I have learnt the basics/intermediate of C++ and I can understand it pretty well.
Ah.
i think jobs care more about good logic being written then the syntax itself or what specific one you know. Ofc if its a job geared towards a certain language then it matters, You can prove you can write good easy to extend code, syntax is kinda irrelevant
Ah
AI can write syntax, but their logic/systems are frail or make no sense
that's where human comes in
you write code for purpose of getting shit done(solving problems?), if you get it done well the language of code is really irrelevant I think
learn c# because it will be useful not only in Unity but the whole .NET ecosystem which is invaluable these days
just a suggestion though, you should really think hard on what you think is best for you
My recommendation is, if you wanna get into it as a career, first talk to local recruiters in your area and find out what your specific area prefers.
Typically a given city/local area usually over time adopts a particular tech stack and it becomes like, 80% of the jobs, because if company A and B use <tech stack> and then company C starts up, they often have 1-2 folks who used to work at A and B so they also wanna use the same stack, and soon enough everyone is mostly using the same stuff.
The vast majority of tech stacks tend to be one of 2 (there's others but I see them way way less often):
-
Asp.Net backend, microsoft stack of Azure, MSSQL, etc.
-
Node backend with express and mongodb, often running on AWS but can run on Azure too
The front end is pretty much always 1 of React, Angular, or Vue, and once you learn one of em it gets very easy to pick up the other 2.
So basically find out which of those is the popular one in your area, and learn that one
Ahh.
There are not many software engineering or IT game dev listings in my area weirdly.
Somewhat of a UI coding issue I believe:
I need it so that when I click the transparent part of a button, it doesn't register as a press (or the raycast just ignores it).
alphaHitTestMinimumThreshold will work for the image if it has alpha built in. However I want to use "Image Type Filled" with a radial fill method and this method doesn't seem to work for that, any ideas?
Thanks
I really didn't want to have to ask for help with this but I really can't figure it out. can someone help me reverse the bulk buy and do it in the bulk sell?
public void CalculateBulkBuyPrice()
{
fakeBulkBuyPrice = 0f;
int fakeBuildingsBuy = upgradesBought;
float currentUpgradeCost = upgradeBaseCost;
for (int i = 0; i < bulkAmount; i++)
{
fakeBulkBuyPrice += currentUpgradeCost * Mathf.Pow(1.15f, fakeBuildingsBuy);
fakeBuildingsBuy++;
}
fakeBulkBuyPrice = Mathf.Round(fakeBulkBuyPrice);
upgradeBulkCost = fakeBulkBuyPrice;
}
public void CalculateBulkSellPrice()
{
fakeBulkSellPrice = 0f;
for (int i = 0; i < sellCorrect; i++)
{
fakeBulkSellPrice += upgradePastCost / 1.15f;
// upgradePastCost /= 1.20f;
}
fakeBulkSellPrice = Mathf.Round(fakeBulkSellPrice);
upgradePastCost = fakeBulkSellPrice;
}
can you first explain a little about the algorithm, for 2 reasons: so I dont assume its doing something its not, and 2 so i can see you also know what its doing
which one bulk buy?
yes, like what the goal is. it looks like each item you buy gets more expensive but a lot of these variables are also not in scope so its kinda hard to run through it in my head
so yeah, its basically to buy a building, it will loop for how many bulkamount is = to, give you the final price of how many buildings you want to buy and how much it will cost correctly. and then in another function use the outcome to do the buy part. but reversing the process has been a bigger pain than i thought it would have been. say i have a building worth 15, next is worth 17, then 20, then 23, then 26 etc
but i want to buy 10 so at a base cost of 15, it will cost me 305 to afford 10.
I want to reverse this process so lets say I have 10 buildings and i want to sell all of them. it will then sell for 305 right? I'm sorry I have just finished my nightshift job and really tired so please excuse me for being a bit overly confused
starting to feel like i had solved it before and just ignored it thinking it was wrong and thats gonna annoy me
nah I'm still very much confused about it
do note I'm not the best at maths
give me one second then to experiment, i think the math part is simple but im just gonna run it through an online compiler before i suggest