#archived-code-general
1 messages · Page 148 of 1
public class Bullet : MonoBehaviour
{
public float bulletSpeed;
Rigidbody bullet;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Rigidbody>();
bullet.velocity = Movement.character.transform.forward * bulletSpeed;
}
// Update is called once per frame
void Update()
{
if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
{
Destroy(bullet);
}
}
}``` whats the correct way to delete this bullet?
can't use this because i think that kills the prefab
Destroy this means you destroy this script attached on the bullet
yeah so what do i supply the param that only kills the single clone?
i tried doing rigidbody and gameobject
Should be fine to just destroy gameObject
if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
{
Destroy(GetComponent<GameObject>());
}```the bullets dont destroy when I do this
Destroy (gameobject)…
I'm surprised that even compiled
That is not a persistent listener (ah, sorry, discord was scrolled up)
oh didnt know gameObject was a supplied param
thought you had to grab it from somewhere
when the main bullet dies im not able to shoot any more
thats probably expected but where do i put the main bullet then if its not supposed to be shot
It's likely u are overwriting the prefab reference then
Because this shouldnt be an issue
void Update()
{
if (canFire && Input.GetMouseButtonDown(0))
{
canFire = false;
StartCoroutine(Cooldown());
Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
}
}``` this is where i make the clones
Bit of a silly question, If I have a ScriptableObject and say I have two references of one in a List or something, are those two seperate instances of that scriptableobject or is it two references to the 1 thing
I believe 1 thing
Unless you do something like... new ScriptableObject?
Should be easy to test
i still havent found out how to correctly destroy the bullet?
What bullet
The one you instantiated?
yup
ik
Okay so destroy that
i can destroy them but then i get errors in console one i try copying more
i think its cause i destroy the original one
public class Bullet : MonoBehaviour
{
public float bulletSpeed;
Rigidbody bullet;
// Start is called before the first frame update
void Start()
{
bullet = GetComponent<Rigidbody>();
bullet.velocity = Movement.character.transform.forward * bulletSpeed;
}
// Update is called once per frame
void Update()
{
if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
{
DestroyBullet();
}
}
void DestroyBullet()
{
Destroy(gameObject);
}
}```
dont look at the DestroyBullet function, i was leaning on chatgpt to help
Ew
lol
Anyway obviously yes. Your original is being destroyed because it's also a Bullet
Wait
How are you assigning the original
Is it in the scene and you dragged it in?
public class FireBullet : MonoBehaviour
{
public GameObject bullet;
public int spawnDistance;
public float fireCooldown = 0.5f;
bool canFire = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (canFire && Input.GetMouseButtonDown(0))
{
canFire = false;
StartCoroutine(Cooldown());
GameObject clone = Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
}
}
IEnumerator Cooldown()
{
yield return new WaitForSeconds(fireCooldown);
canFire = true;
}
}```
Where is your original bullet
its public GameObject bullet; up there
And what are you dragging in
a sphere
Show me in your editor, what did you drag in
That sphere in the scene?
yup
You should make it a prefab, and drag the prefab in instead
how i do that
Then it won't run Update since it's not in the scene, and it won't destroy itself
drag sphere into editor project file*
When it becomes blue then it's a prefab, drag the prefabs onto your serializedfield
By learning some basic unity
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
Prefabs are essential
i know c#, just not unity ui ¯_(ツ)_/¯
Okay, you can learn. I don't have time to handhold right now. You're asking in code general, I assume basic knowledge
Bye
wowza
Just look up how to make a prefab
@jade phoenix
oh alright
Make sure to drag the prefabs from project file and not from scene.
can i delete the sphere from the scene now?
Yes, you can.
Noice, Instantiated object usually from prefabs, so it'll not referencing to any other active gameobject.
On another tips, you can use SerializeField tag to improve class encapsulation, while you can access it on the inspector,
public class FireBullet : MonoBehaviour
{
[SerializeField]
private GameObject bullet;
[SerializeField]
private int spawnDistance;
[SerializeField]
private float fireCooldown = 0.5f;
bool canFire = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (canFire && Input.GetMouseButtonDown(0))
{
canFire = false;
StartCoroutine(Cooldown());
GameObject clone = Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
}
}
IEnumerator Cooldown()
{
yield return new WaitForSeconds(fireCooldown);
canFire = true;
}
}
alright so i sorta wanna do the same thing with a text ui element, where it pops up on the screen for a few seconds and then fades away and destroys itself
do i need to prefab canvas or just text
For me I'll only prefabs text, since there's only usually only one (screen space ui canvas) in my secene.
actually i could probably just keep it alive at 0 opacity
would that cause performance issues?
No, if you're not instantiated a lot there's no problem.
And just another tips, destroying an object is actually expensive.
Like your bullet, you should re-use the bullet instead of destroy it, hide the bullet somewhere else, use it when shoot, in some range hide it again.
is that like a garbage collector thing or?
We called it as pooling, it's a design pattern try to avoid instantiation cost.
So usually we instantiate in scene load how much bullet we wanted to use, and just recycle it.
Because instantiation is expensive.
hm alright ill just set the opacity to 0 and keep it on screen then
Text text;
void Start()
{
text = GetComponent<Text>();
text.alignment = TextAnchor.LowerCenter;
text.rectTransform.position = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f);
}``` is this the correct way to center a text element on the screen?
may I have help with this?
theres a bit more information above the replied message
.
Sadly I has never use voronoi.
You can center it in inspector.
how make a input buffer?
if you have basic in css/winform you know that playing with canvas is similar to playing with panel, create a panel that stretch's full screen and put your text inside and center it,
Can you elaborate more?
I want an input to be saved for a few seconds and then deleted, so that if, for example, I press up 3 seconds before touching the ground, when it touches the ground the action is executed
What type of input to be saved? For ground touch you can look up on Trigger/Collision
if be saved a Keycode
wait
Then maybe you can just make an if statement and set bool isKeyUpPressed value of that key pressed when you press up 3 seconds before touching the ground.
If you need exact 3 seconds, then you can count the seconds if they keypressdown pressed in that 3 seconds frame then set bool to true.
Cool!
Maybe you can check if the file path valid?
If not valid, there's two ways to think about is, resources folder OR check if not exist then create new json file on disk.
Hey folks. I'm trying to improve the algorithms used in my game to better position melee units as they engage in battle. It is an RTS with a top-down view, and at the moment each unit periodically does a circle collider cast to locate enemies, and then enters an engagement state machine which iterates them next to the enemy to fight. But this has two problems. The first is the enemy is often moving too, and units only process their state machine every 250ms to save on resources, which can lead to them intersecting or crossing paths which gets messy. The second issue is units often end up overlapping where they stop moving and begin slugging it out. I've been hesitant to make use of colliders and collider callbacks due to the physics overhead. In any case, I'm not expecting a real "here's how to fix this" but more of a - do any resouces exist that deep-dive into game design theory that might help give me insight into possible methods for improving this?
@exotic aspen i can think of something that might help... if your problem is the constant 250ms delay between "AI ticks" then make that delay variable, based on distance to the closest object of interest.
@mellow night True, variable think rates are an option to help align things better. I'm just wondering if there should be a larger framework for positioning things. For example I'm toying with the idea of a manager class that assigns positions for all units engaging in combat and ticks at a fast enough rate to keep track of stuff.
Two or more enemies enter combat, they register where they will be stopping to whack each other at. Then as more join the fight they register their positions. This prevents many of the above issues. The challenge of course is maintainance and cleanup, and making it look organic.
well it depends how you guys move exactly bu i might have an idea for that too!
At the moment I'm using the A* Pathfinding Pro Asset which helps with movement. Every unit has a destination they are moving to, and a state machine to manage that and what happens when they arrive at their destination.
you give each unit a sort of "anti gravity" or a repulse value based on 1/distance squared. each unit has a target vector pointing towards their actual target, but that vector is affected by other nearby objects, it makes sort of flocking behaviour where units will hold formation and gently curve away from and around obstacles
:nod: The Asset actually has crowd movement mechanics you can enable. But there's a lot of tuning required to make it so units don't permanently shake in place sort of thing. I've avoided using physics so far due to the high CPU consumption on mobile. I have colliders for raycasting, but no actual units bumping into each other at the moment. I was surprised how much just friction with the ground was slowing the engine down at 10k units, and reduced the physics accuracy a bit to compensate.
heh, i have done a similar thing on this project, got rid of all rigidbodies, but now i want to do collisions bewteen convex mesh colliders, and ooh boy, thats a headache
my reasons weren't about performance of the physics engine though, more that is just not suitable because my game isn't strictly 2D or 3D. Rather than fixed x ,y or z everything is at a fixed distance from origin, so I was constantly having to fix and overide they standard physics, in the end I ditched it but went with sphere colliders on everything for simplicity
regarding unit shaking at destination though, cant you just give them a bit of tolerance? make the distance they stop moving smaller than the distance the triggers them to start moving
:nod:
Well it’s more the repulse effect has trouble settling down. I’ve not experimented much with it. Just visited their discord and observed folks having trouble with various attempts at it.
Big picture though, I’d love to see the white boarding devs as a team can do to ideate and solve complex problems such as these.
Does anyone know how i could make it so when i die in my 2D game my characters freeze rotation turns off so that my character become able to fall over and stuff?
Cross posted, already resolved #💻┃code-beginner message
I am trying to modify the IAPButton script which is offered via the In-App Purchase package in the Package Manager. I am trying to add 'using TMPro;', but the namespace is not recognized and it's giving me type or namespace could not be found. all of my other scripts using TMPro still work fine... any help?
I am adding camera shake to my player controller, and I've encountered and issue. Here is my script: https://hastebin.com/share/iporelosoh.csharp. Here is a video of the issue: https://streamable.com/h7ckwn.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
stops abruptly?
It stops with a weird delay, it takes a while to stop.
Could be an assembly related issue, is that script a part of a assembly definition file in your assets folder structure or does this script exclusively exist in the "Packages" folder?
Try replacing all the GetAxis with GetAxisRaw
void CameraShake() {
if (isSprinting && Input.GetAxis("Horizontal") != 0 && Input.GetAxis("Vertical") != 0) {
cameraShakeManager.RunCameraShake();
}
if (isCrouching && Input.GetAxis("Horizontal") != 0 && Input.GetAxis("Vertical") != 0) {
cameraShakeManager.CrouchCameraShake();
}
if (!isCrouching && !isSprinting) {
cameraShakeManager.WalkCameraShake();
}
if (!isCrouching && !isSprinting && Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0) {
cameraShakeManager.StandCameraShake();
}
}
That fixed it, but now it does just stop abruptly
The In App Purchasing folder is in Packages, while the TMPro folder is in Assets
Anyone have any idea where to start looking for this issue with ScreenPointToRay? Every second frame or so the location flickers to a different one, and then back again. The mouse coordinates didn't change, and the camera is slightly moving (miniscule amounts, -22.997001 -> -22.99685 etc). Could this just be floating point errors exploding?
How are you trying to modify the IAPButton script from Packages?
just clicking on the gameobject that has IAPButton in the scene and then clicking edit script
It stops on time now, but it stops abruptly
The abrupt stopping is because you stop calling the Shake function right away when the if statement is false /input stops
I have this issue on some of my motion logic, im still trying to find an efficient way to smooth it out once the input is no longer given / the if statement is false
So I dont really know how to fix that myself
ill be working on a similar thing today anyways, im gonna ping you if I find a solution
Huh, AFAIK, I dont think you can edit scripts in the Packages folder, but you can see the code, just the script itself would be "locked" from editing, if the package itself doest depend on TextMeshPro, you may either have to duplicate the script so it gets added to your Assets folder structure (and can therefore edit it in the default assembly), or create a new script that inherits from that script, and try to extend it, if you are currently able to edit the package script, id be curios where that edited file is being saved
Alright cool, thanks.
If you replace Input.GetAxis("Horizontal") != 0 with Mathf.Abs(Input.GetAxis("Horizontal")) > 0.5f (and the same with vertical axis) you can shorten the delay. Adjust the 0.5f value to liking
and it should be if (isSprinting && (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)) anyway, otherwise it only shakes when moving diagonally
Anyone have any idea where to start
textIndexrepresents current TMP_Text used to type text. currLine represents current line of all these textComponents
sorry, I was away for several minutes
you can see textIndex and currLine in console
Hey so I've been working on a project in which i need a player to be able to essentially copy the rotation of other objects - my approach for this has been to take set the player's transform.up as equal to the target object's transform.up. This has been working and the player gets the correct direction, but an unintended side effect is that the other directions of the player are sometimes rotated too. In the 3 videos attached, i've got a very basic version of the system which showcase the error, which i'm currently using while i try to figure out a way to make rotation behave as intended. The green line is the up direction. When the system works as intended, the up vector rotates to be equal to the target object while moving the other directions as little as possible, which the first video demonstrates. The issue is, sometimes transform.up will add unnecessary rotation, which can mess up player aiming.
Code is here, but it really is just lerping from one direction to the other.:
public class CloneDir : MonoBehaviour
{
public GameObject obj;
float slerpT;
Vector3 startUp;
Vector3 endUp;
// Start is called before the first frame update
void Start()
{
startUp = transform.up;
endUp = obj.transform.up;
Debug.Log(startUp);
Debug.Log(endUp);
slerpT = -0.5f;
}
// Update is called once per frame
void Update()
{
transform.up = Vector3.Slerp(startUp, endUp, slerpT);
slerpT += Time.deltaTime;
if (1f < slerpT && slerpT < 1.002f)
{
Debug.Log(transform.up);
}
}
}```
Does anyone have any ideas for how i can make this work better? I'm rather stumped here.
when you say essentially copy the rotation of tyhe other objects
whats the goal
So the overarching system I'm trying to implement is basically a system where the player has a gravity gun and when they shoot a wall/roof/whatever, that becomes the floor and so the player rotates to be perpendicular from that surface.
and that works, but in the process the camera gets messed up and can sometimes rotate by 90 degrees
I think its better to not copy other objects rotations person but to copy the up direction
yeah, that's what i'm doing
kinda get what you're tryna pull off
this code just takes the other object's up direction, the player object's up direction, and spherically interpolates the player's up direction from the player's to the target's
on the videos
where the rotation is long and unnessecary
what is the rotation of the object the players following?
in that particular example, the target's rotation is 90,90,0 and the player's rotation is 0,0,90
i guess the fact that they're all opposite could be causing issues
hang on for a moment, i may have found a method that works
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/ I suggest for lerping to look at this article i found it very helpful for lerping
Okay, the method i found does clear all 3 previous examples working as intended so I'm going to say it works for now. Still, thanks so much for taking the time to help - I'll check out the article as well.
curious what it changed? 😄
https://gamedev.stackexchange.com/questions/194641/how-to-set-transform-up-without-locking-the-y-axis
Found this article buried in google searches which was what i was looking for, and the reply gave me this code
which works a charm
maybe because you haven't used previous Slerp correctly?
that may be an issue but i did try it without slerping, just directly setting transform.up = target.transform.up and it had the same issue
oh well
problem solved now
why do you even set transform.up
because the feature im working on is a gravity changing gun and the easiest way i could think of to do that was to make gravity always apply downward and then just copy the up direction of whatever surface's direction i'm copying
did anyone know about Newtonsoft error?
I am currently using raw Rotate and Translate calls on a model and all was working fine, but I was getting some awkwardness with motion in animations, so I turned of Apply Root Motion, my understanding was that root motion basically moved the model based on animations rather than manual movement logic, so is my understanding wrong here? or should turning off root motion stop manual movements?
Can you use operators for conditional compilation? I.e: #if UNITY_ANDROID || UNITY_IOS
ye
I did it and it worked, thank you!
Buuuuut I have a new issue now! The collisions no longer work... Would you have any idea how I could fix this without requiring two meshes?
public Mesh createMesh(List<Vector3> vertices, float thiccness, float offset)
{
Mesh mesh = new Mesh();
mesh.subMeshCount = 3;
float topHeight = thiccness * (offset+1);
float botHeight = thiccness * offset;
//VERTICES
Vector3[] meshVertices = new Vector3[3*2 + 4*3];
Vector3 vecATop = vertices[idA] * topHeight; //A Top
Vector3 vecBTop = vertices[idB] * topHeight; //B Top
Vector3 vecCTop = vertices[idC] * topHeight; //C Top
Vector3 vecABot = vertices[idA] * botHeight; //A Bot
Vector3 vecBBot = vertices[idB] * botHeight; //B Bot
Vector3 vecCBot = vertices[idC] * botHeight; //C Bot
//!VERTICES
//TRIANGLES
int topChannel = 0;
int sidesChannel = 1;
int botChannel = 2;
//TOP
meshVertices[0] = vecATop;
meshVertices[1] = vecBTop;
meshVertices[2] = vecCTop;
int[] topTriangles = new int[3]
{
0, 1, 2
};
//!TOP
//SIDES
//AB
meshVertices[3] = vecATop;
meshVertices[4] = vecBTop;
meshVertices[5] = vecBBot;
meshVertices[6] = vecABot;
//!AB
//BC
meshVertices[ 7] = vecCTop;
meshVertices[ 8] = vecBTop;
meshVertices[ 9] = vecBBot;
meshVertices[10] = vecCBot;
//!BC
//AC
meshVertices[11] = vecATop;
meshVertices[12] = vecCTop;
meshVertices[13] = vecCBot;
meshVertices[14] = vecABot;
//!AC
int[] sideTriangles = new int[6*3]
{
//AC
5, 4, 3,
5, 3, 6,
//!AC
//BC
10, 7, 8,
10, 8, 9,
//!BC
//AC
14, 11, 12,
14, 12, 13
//!AC
};
//!SIDES
//BOT
meshVertices[15] = vecABot;
meshVertices[16] = vecBBot;
meshVertices[17] = vecCBot;
int[] botTriangles = new int[3]
{
15, 17, 16
};
//!BOT
//!TRIANGLES
//UV
Vector2[] uv = new Vector2[18]
{
//TOP
new Vector2(0 , 0),
new Vector2(0.5f, 1),
new Vector2(1 , 0),
//!TOP
//AB
new Vector2(1 , 1),
new Vector2(0 , 1),
new Vector2(0 , 0),
new Vector2(1 , 0),
//!AB
//BC
new Vector2(1 , 0),
new Vector2(1 , 1),
new Vector2(1 , 0),
new Vector2(0 , 0),
//!BC
//AC
new Vector2(0 , 1),
new Vector2(1 , 1),
new Vector2(1 , 0),
new Vector2(0 , 0),
//!AC
//BOT
new Vector2(0 , 0),
new Vector2(0.5f, 1),
new Vector2(1 , 0),
//!BOT
};
//!UV
mesh.vertices = meshVertices;
mesh.SetTriangles(topTriangles, topChannel);
mesh.SetTriangles(sideTriangles, sidesChannel);
mesh.SetTriangles(botTriangles, botChannel);
mesh.uv = uv;
//Calculate normals (optional)
// mesh.RecalculateNormals();
// Return the created mesh
return mesh;
}
Any idea how to get my collisions back to working now? '^^ My MeshCollider broke
you can manually generate a mesh like the one you had before, attach the mesh renderer, create the collider, and then create the desired mesh. The previous mesh collider will remain iirc
otherwise create a 'half-cube' from blender and export it, and have it on your object as a collider 😛
I not sure what is going on here but when I instantiate some objects at run time in Scroll View and I set their layer below some other canvases I have in the scene the instantiated objects still appear above them. Anyone know why?
Thank you Lyrcaxis! ❤️
np 🙂
Unity UI uses hierarchy index as fallback depth sorter
The only other way to change this is to use layer/sorting order on the canvas component itself
There is 2 lines per index ? What you want ?
textIndex = currLine / 2 ?
0 / 2 = 0
1 / 2 = 0
2 / 2 = 1
3 / 2 = 1
4 / 2 = 2
5 / 2 = 2
...
Hmm I tried using the layers and sorting order but still nothing and now I tried the hierarchy index as well but the instantiated objects seem to ignore it all
Bing says it is a known bug but not sure
Show pics?
The find panel is the object at the side that the images are positioned above
I made the layer UI Top to try and position it on the top but didn't work
Everything else is in the UI layer
Hello all.
I have a problem.
my siprateRenderer object is disappear after dragging. Help me😢
Code is here
https://codeshare.io/pqdYR4
i check order in layer all good
That's a sprite renderer, shouldn't be UI
For UI ppl use the Image component
Otherwise u run in all kinds of issues, especially with ordering 😄
@stable osprey Oh well thats good to know thanks!
np
Reset() is basicly what happens when you use the Reset option on a component?
does it run when you first create the component
In the editor, yes
Hello, i have a mesh that is attached to another mesh the structure looks like this:
Character
Ring
I have a script attached to the Character, how should i access ring's render for the script??
ideally you should reference it via the inspector.
But if you're 100% set on not doing that, you could use transform.Find("Ring").GetComponent<MeshFilter>().mesh
what is inspector??
Not necessarily a unity question so I hope this is ok, but does anyone have some experience with VSCode custom tasks?
I'm trying to create a simple task to execute a bash command to run a linter on the current open file and return any errors in the terminal.
I got it to "run" once, but it never seemed to complete, and when I tried to run the task again it said it was already running
Hi guys i was wondering if anyone have any kind of troubles when a Android device change his current refresh rate.
Im getting this error:
Java_com_google_androidgamesdk_SwappyDisplayManager_nOnRefreshRateChanged
So there is anyway in unity to hook to an event that check the current refresh rate?
You should search through the Android Documentation and Sample with Unity.
And what is the error specifically ? Because this is not an error.
So if I still remember maths from 5th grade
currLine = (int)(textIndex * 2);
No.
This is wrong.
You cannot know the amount of line from the textIndex
There is two possible answer.
Because of the floor operation.
currLine will either be (int)(textIndex * 2); or (int)(textIndex * 2) + 1;
(int)9.99f = 9
Yes, this is the issue.
yeah, or (int)(textIndex * 2) + 2 if 3 lines
but I don't count middle lines
?
3 lines
If you want to know the amount of line from the index you cannot.
n, n + 1, n + 2
Because there is two answer.
It is not what I am doing.
for projectiles is velocity or transform.position better? just in general
im reading mixed things
If you have 3 lines per index, there is 3 possible answer for the amount of line given an index.
no,
(int)(textIndex * 3); or (int)(textIndex * 3) + 1 or (int)(textIndex * 3) + 2
it's either +1 or -1 if difference is 1 line
int diff = value - textIndex;
if (diff != 0) currLine += diff * textLineCount - (diff > 0 ? 1 : -1);
so I have done it in this way.
diff is text index offset
value is in set =>
value is future textIndex
so textIndex + 1 if += 1
but that's not really maths
So, the answer is currLine = (int)(textIndex * 2) + diff
why do you (int) it?
it won't ever be float
I just copied what you have written
man everyone has a different answer for this. annoying
(And you are right, you do not need the (int))
I have tried to implement formula from your previous reply.
this one
oh, yeah
?
so I am probably looking how to implement this with just maths
What do you mean...
the reason im worried is there will likely be a lot of projectiles eventually, so i dont know if transform every update is a good idea
why don't use lambda operators in maths, do we?
What you want ? Line in function of index ?
just maths.
I gave you the math
I am just not that good in maths
?
I explained to you that you cannot find the answer with just math
hello everyone
Because there is 2 answer.
Are there any algorithms that can suggest the optimal shot in a snooker game ?
am working on a project which aims to make an automatic cue for a snooker game
Rigidbody.velocity is the most stable version. (In general)
if diff is 1 or -1 => currLine += 1
if diff is more (or less) => it's += textLineCount for each 1 or -= textLineCount for each -1
thats what I figured, i just didnt know if the physics might get fussy
How diff is defined ?
I had this in my previous message
int diff = value - textIndex;
value is setted new textIndex
private void SetTextIndex(int value, bool alignCaret, bool removeText = false)
So, you are setting the text index and the line at the same time ?
yeah,
actually I don't really need to I guess.
for now
though it should be set actually
I now just change lines when text is wrapped
so when TMP_Text's width exceeds maxWidth
If you only have 2 lines, I guess you can use it to know if the answer is
(textIndex * 2) or (textIndex * 2) + 1
if diff is negative - it can only be (textIndex * 2), logically
otherwise (textIndex * 2) + 1
when typing
(textIndex * 2) + (diff != 0 ? 1 : 0)
(textIndex * 2) when deleting
However, that will only work if you set the textIndex when you change line.
maybe you mean value here?
currLine = (value * 2) + (diff != 0 ? 1 : 0)
If text index is updated multiple time inbetween line change. Diff will not be correct.
what do you mean by multiple time?
you mean that method is called multiple times?
Exact
it will be executed fast enough
If you call the method twice, diff will be always be equals to 0.
It has nothing to do with how fast it is exected...
if will also equal 0 first time textComponent is set
Not an issue. The first time it most be equal to 0.
So, yeah, if you do not call set index each time you change line and (only then), it is not gonna work.
it won't work
but, actually, if we use value * textLineCount
I think is should then be + (diff < 0 ? textLineCount - 1 : 0)
currLine = (value * textLineCount) + (diff < 0 ? textLineCount - 1 : 0)
that should work.
@steady moat thank you for your help!
I want to make a tetris like inventory system in Unity (Like dayz, tarkov, unturned)
I am wondering what the best way is to visualise this. I would love some kind of visual representative in the editor but if I think of how I would do it in editor (basically grid layout with cells and then some kind of image on top for the division of cells) I am struggling to find a way to detect which cell object corresponds with the internal grid code
Any suggestions or help?
Why might this be happening with the weapon following the characters mouse. I'm using a raycast to find a point
custom editor script or script that runs in Editor mode or use tilemap maybe ?
it's happening because your code is faulty. Can't say more than that without seeing said code
show script
How would that custom editor script work on a high level? How would a tilemap help?
well if you think about it Tilemap is just a Grid , so it would theoretically be possible to make one just be used for inventory only
I'm using the new input system and I have my EventSystem configured with the "Left Click" set to the Mouse Click action in the UI map. This Mouse Click action is a button with a binding where the Trigger Behavior is set to "Press Only" but when I click something in the UI, it's fired on press and on release. How can I make it so that is fired only on press?
Custom editor script would be used if you do it with a 2D array or something @wise arch
then you can visualize it without being in playmode
Yeah that's what i currently have in my code
public class GenericGrid<T>
{
private int _width;
private int _height;
private float _cellSize;
private Vector3 _originPosition;
private T[,] _gridArray;
// ...
}
your raycast is very weird
yea why is it transform.up lol
Just messing around and it was the only one moving for some reason
Vector2 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 gunDirection = (worldMousePos - (Vector2)transform.position).normalized;
GunLocation.right = gunDirection;```
Using a physics raycast really doesn't make sense.
So would it be like if you change the width and height in the inspector it changes the grid in the editor?
well yea
I'll try it
https://docs.unity3d.com/ScriptReference/ExecuteAlways.html
you can use this too
That is very interesting
edited it , use new one. according to docs is better
Seems weird that execute always is better than not always hha
I'm trying to make a 2d chess game and I don't know how to implement En Passant
This attribute is being phased out since it does not take Prefab Mode into account. If a Prefab with a MonoBehaviour with this attribute on is edited in Prefab Mode, and Play Mode is entered, the Editor will exit Prefab Mode to prevent accidental modifications to the Prefab caused by logic intended for Play Mode only.
To indicate that a MonoBehaviour correctly takes Prefab Mode into account and is safe to have open in Prefab Mode while in Play Mode, the attribute ExecuteAlways can be used instead of the attribute here.
Okay I see
So if I use this attribute I assume I make the visual parts of the grid in code?
that's usually how is done is with code 😛
you could probably do it with tilemap too tbh it's a 2D array-like grid as well
Yeah fair haha but Imean there is a way that I would read and count the children and determine the grid from there but it would be a hassle
I'm trying to use System.Management to get some more detailed info about com port devices. System.Management is not implemented in Unity/Mono. I made a plugin to try and get around this, but I just get a NotImplementedException thrown at me.
Does anyone have any recommendations for a workaround here?
you tried adding a managed library (dll)
?
Yes, but I'm not confident I did it correctly
well how did you do it?
Right. This is only a personal use thing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Text.RegularExpressions;
namespace ComPortInfo
{
public class ComPortInfoClass
{
public struct ComPort // custom struct with our desired values
{
public string name;
public string vid;
public string pid;
public string description;
}
public int doThing()
{
return 47;
}
private const string vidPattern = @"VID_([0-9A-F]{4})";
private const string pidPattern = @"PID_([0-9A-F]{4})";
public List<ComPort> GetSerialPorts()
{
using (var searcher = new ManagementObjectSearcher
("SELECT * FROM WIN32_SerialPort"))
{
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
return ports.Select(p =>
{
ComPort c = new ComPort();
c.name = p.GetPropertyValue("DeviceID").ToString();
c.vid = p.GetPropertyValue("PNPDeviceID").ToString();
c.description = p.GetPropertyValue("Caption").ToString();
Match mVID = Regex.Match(c.vid, vidPattern, RegexOptions.IgnoreCase);
Match mPID = Regex.Match(c.vid, pidPattern, RegexOptions.IgnoreCase);
if (mVID.Success)
c.vid = mVID.Groups[1].Value;
if (mPID.Success)
c.pid = mPID.Groups[1].Value;
return c;
}).ToList();
}
}
}
}```
What I'm not confident about is which System.Management I should be referencing
How can i check if a certain collider will collide with anything if i move it to a specific position
Obviously before moving
make a overlap the size of the collider physics check
to the location
That doesn't really help if i have a complex collider
!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.
define complex collider
Mesh collider/different colliders together under the same object
I want to be precise
Edited the code block
With multiple colliders i can maybe handle it by iterating over them and checking each one.
However to a mesh collider i have no idea
did you export this using Visual Studio with the correct settings?
you should be using it as a Class LIbrary
It compiles, Unity is happy with it, and when I had other simple functions in the ComPortInfo class, they worked. It's just the ManagementObjectSearcher where I keep getting the not implemented exception
NotImplementedException: The method or operation is not implemented.
System.Management.ManagementObjectSearcher.Get () (at <76ecc80888b243be801ffc133a5b2fc8>:0)
(wrapper remoting-invoke-with-check) System.Management.ManagementObjectSearcher.Get()
ComPortInfo.ComPortInfoClass.GetSerialPorts () (at <2432236533334f279a1f9bad52c6787b>:0)
PicoController.Start () (at Assets/Scripts/PicoController.cs:30)
From my limited understanding, Mono does not implement the managementObjectSearcher, but I don't know how to get Unity to ignore the Mono version of System.Management and only reference the one I referenced in my dll
oh this is for some type of IOT devices ?
Eh, sorta. Microcontrollers. Raspberry Pi Picos and/or Arduinos.
I/O for an escape room
I have no way to test it myself so I can't offer much help, I don't have experience with controllers and unity :\
sor
https://forum.unity.com/threads/proper-method-to-reference-system-management-in-unity.977796/
this only info I found, it barely helped
No worries. Technically I'm not even at the point of testing it with a Pico. Just trying to get the stupid dll to use the right system.management
Ha, yeah the last comment in that thread is from me
oh haha was wondering the date "what a coincidence lately "
I have this script using the new input system , I have an issue I need help with , My movement is working except when I release the movement keys my character slides in the direction I was last moving in , I want it to stop when movement keys are released
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private float speed;
[SerializeField]
private Rigidbody2D playerRigibody;
[SerializeField]
private Animator playerAnimator;
[SerializeField]
private PlayerInput playerInput;
private Vector3 positionChange;
private PlayerInputActions playerInputActions;
private Vector2 inputVector;
private void Awake()
{
playerRigibody = GetComponent<Rigidbody2D>();
playerAnimator = GetComponentInChildren<Animator>();
playerInput = GetComponent<PlayerInput>();
playerInputActions = new PlayerInputActions();
playerInputActions.PlayerControls.Enable();
}
private void FixedUpdate()
{
inputVector = playerInputActions.PlayerControls.Movement.ReadValue<Vector2>();
playerRigibody.AddForce(new Vector2(inputVector.x, inputVector.y) * speed, ForceMode2D.Force);
if (playerInputActions.PlayerControls.Movement.ReadValue<Vector2>() != Vector2.zero)
{
playerAnimator.SetFloat("MoveX", playerInputActions.PlayerControls.Movement.ReadValue<Vector2>().x);
playerAnimator.SetFloat("MoveY", playerInputActions.PlayerControls.Movement.ReadValue<Vector2>().y);
playerAnimator.SetBool("IsMoving", true);
}
else
{
playerAnimator.SetBool("IsMoving", false);
}
}
}
then you probably need more friction or to do your own friction
by adding force in the opposite direction of the current velocity
newton's second law is relevant here
if (inputVector.magnitude < 0.01f) playerRigidbody.velocity = Vector2.zero;```
or yes, stop by adding forces
but - you know - it's a physics sim
it does physics things
as ME2 taught us, Sir Isaac Newton is the deadliest son-of-a-bitch in space
newton's first law baby
wait it was the first law
dammit
I was thinking of the second law of thermodynamics
😭
yeah I tried inputVector = Vector2.zero
well, that would just make your input vector be zero...
that makes... very little sense
That's basically saying "if input is zero, make input zero". Think about that for a sec.
well, on its own, it's just "input vector is always zero"
adding forces changes the velocity. If you don't do any change... you are left with the current velocity not changing
i can't quite tell if that's a typo'd conditional or just a statement on its own
Dont use .AddForce in this case, you just wanna do
playerRigibody.velocity = new Vector3(...)
or Vector2 if its 2d
if you are just wanting "hairpin" start/stop char control where as soon as you hit left, you go left, and as soon as you let go, you stop going left
.AddForce is meant for "coasting" style where you will ramp up and ramp down your speed, resulting in a build up to max velocity, and then a slow down to 0 on release
if you do want the ramp up/down still but just faster, thats primarily achieved by modifying the characters Rigidbody properties to change friction values and mass
Yes , THis is the wayI want it , I still get "Drift" when changing directions like going for just left to just down I have a bit of a curve
Like this
Thank you stops all drift while moving and changing directions
what's the point of your inputVector variable if you're going to repeat that long-ass ReadValue line 4 times 😢
Oh yeah lol , I already spotted that and fixed it
You do not want to update animation in FixedUpdate. In fact, you do not even need fixed update here as you use velocity.
Use what regular update or Fixed?
Also, is your input updated in FixedUpdate ?
Only Update
.velocity set the velocity of the rigidbody which will be move in the fixed update.
If you were increasing the velocity, that would have been different.
Move the animation update into the Update();
Haven't done opitmization yet just getting started , was using old input system , just trying to swap it over to new input system
Like
private void Update()
{
inputVector = playerInputActions.PlayerControls.Movement.ReadValue<Vector2>();
if (inputVector.magnitude < 0.01f)
{
playerRigibody.velocity = Vector2.zero;
}
if (inputVector != Vector2.zero)
{
playerAnimator.SetFloat("MoveX", inputVector.x);
playerAnimator.SetFloat("MoveY", inputVector.y);
playerAnimator.SetBool("IsMoving", true);
}
else
{
playerAnimator.SetBool("IsMoving", false);
}
}
private void FixedUpdate()
{
playerRigibody.velocity = new Vector2(inputVector.x, inputVector.y) * speed;
}
Thank you
Hey there.
So I have two objects in my scene and I'm trying to make object A move to the position of object B using DoTween. I tried doing this with DoMove and it works. The problem is that the target object (B) is moving. So when I call DoMove I give it the position of the target at that moment, but if object B moves away, my object A doesn't follow the new position of the target.
I'm not sure how to fix that. 🙂
using UnityEngine;
public class DiveController : MonoBehaviour
{
public float diveForce = 10f; // The force applied when diving
private bool isDiving = false; // Flag to track if the object is currently diving
private Rigidbody rb; // Reference to the Rigidbody component
private void Awake()
{
// Get the Rigidbody component attached to the object
rb = GetComponent<Rigidbody>();
}
private void Update()
{
// Check for input to initiate a dive
if (Input.GetKeyDown(KeyCode.G) && !isDiving)
{
// Apply the dive force in the upward direction
rb.AddForce(Vector3.up * diveForce, ForceMode.Impulse);
// Set diving flag to true
isDiving = true;
// Call a coroutine to reset the diving flag after a certain duration
StartCoroutine(ResetDivingFlag());
}
}
private IEnumerator ResetDivingFlag()
{
// Wait for a certain duration before resetting the diving flag
yield return new WaitForSeconds(1f);
// Reset the diving flag
isDiving = false;
}
}
You need to format !code correctly.
You also need to post a question if you're having an issue with this.
📃 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.
smells like ChatGPT
A lot
Oh yeah, now that I see the very obvious comments
player.Kill(); // Kill the player
(Every line is commented)
and apparently diving involves moving upwards in gptland
dive into the cosmos
Hey guys. I would like to create a turn system
Do i use State for that ?
Case turn1
Case turn2
Etc ?
No.
Ok that was m'y first idea
Do I need to stop Coroutine in OnDestroy()?
is it running from destroyed object ?
You do not need.
don't think it matters once it's destroyed coroutine is gone
yeah.
ok, thanks
OverlapSphere returns multiple colliders at once, in an array. Your variable must be of type Collider[].
Next time post the error message that goes with the code, we're not compilers
I don't know if this belongs here, but I'm trying to disable movement when an object is held using an interaction ray. Also ignore the file name/commented out code, its reused because i didnt need it for its original purpose.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class ActivateGrabRay : MonoBehaviour
{
// public GameObject leftGrabRay;
// public GameObject rightGrabRay;
public XRRayInteractor rightRayGrab;
// public XRDirectInteractor rightDirectGrab;
public LocomotionSystem ContinuousMoveProvider;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// leftGrabRay.SetActive(leftDirectGrab.interactablesSelected.Count == 0);
// rightGrabRay.SetActive(rightDirectGrab.interactablesSelected.Count == 0);
ContinuousMoveProvider.enabled = (rightRayGrab.interactablesSelected.Count == 0);
}
}
is subscribing to events usually done in OnEnable()?
Wherever necessary but yes, that would be a spot - assuming subscription is removed on disable
That's what I prefer, and unsubscribing in OnDisable(). I've seen people use Awake and OnDestroy, but that could be confusing because the subscription will still be active even if the script or game object is disabled.
It would be fine if the object is to be instantiated and destroyed only but enable and disable would be a better practice unless they explicitly do not want it to occur during those steps.
ok, thanks
Hi, I was wanting a joint to rotate freely (using a CharacterJoint at the moment), for instance the rigidbody the joint is connected to is constantly spinning, I want the joint to just act as a joint and not break or have a limit on how much the gameobject can twist etc before it spazzes out.
Thanks in advance
Why is Delete key not included in Keyboard.current.onTextInput?
It was actually not an issue - I had forgotten that I deattached my collider because it wasn't happy about me messing with the mesh a day or two ago!! :3
Just curious with most Unity functions if you hover over them it gives a brief description. How could one do this?
Oh wait
for C# in Visual Studio just type /// above the item (works for classes, functions, attributes, properties, everything)
Hell yeah cheers!
I think also works in VS Code too :3
Hello guys!
I need some information. I'm starting the test phases to publish a game on Google Play.
I am able to Run and Build using my device (Samsung Note 10)
But I can't download the test version from Play Store. It says that my device is not compatible.
I already checked the Android version and it is supported. Any clues?
Ask in #📱┃mobile
What if the overlap detects two objects, but the player comes second in that array?
the layermask could be wrongly configured
the player could be missing colliders
the player layer could be wrong
the player could not be in the area
You need to loop through the array with for or foreach, to scan all elements of that array.
It is actually designed to detect multiple players but for now I want it to only get the first one
Then you need so debug things, is this code getting executed at all? How much elements are in the array? If there's some, what's the object names these colliders are attached to?
Is there a way to cast UnsafeList to NativeList, or do a memcpy or something
The code is executed because it gives me false all the time, the array is always empty even though I have the player with the correct LayerMask and the IAController searches for that layermask.
Okay, just for testing remove the layer mask and try again
CopyFrom was the first thing I checked
Guess I need to update my packages (it only showed T[] and NativeArray<T> as options)
cheers
Seems to appear in version 2.1.4
That seems to have worked, I changed the layermask from a prefab to a gameobject and now it works
Okay, for reference if you need to make a layer mask easily there's the LayerMask type, it gives you a nice dropdown in the Inspector when you make a field
Ah guess I'm not on a high enough Unity version for 2.X. Not sure I really want to update to 2022 just yet, maybe I can backport the change. Or bite the bullet and upgrade. Hmm
You probably didn't configure it correctly if you used bit ops 1 << layer, or used the layer directly (a layer is not a mask)
Yes, that's exactly how I do it.
show the code
So you're saying the layer was not actually set properly on the object that had the collider
Incidentally, doing NativeList.GetUnsafeList()->CopyFrom works, and is what the new NativeList CopyFrom overload does internally. So that makes things easy
anyone have any ideas on this?
Warning CS8032 An instance of analyzer Unity.MonoScriptGenerator.MonoScriptInfoGenerator cannot be created from C:\Program Files\Unity\Hub\Editor\2022.3.4f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file
specified.. Assembly-CSharp C:\Program Files\Unity\Hub\Editor\2022.3.4f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll```
it's only a warning but looks severe
and probably related, a new class I've put in for enemy movement is acting strange
runitme is not making sense
can someone help me with this code, I'm trying to make component to make clickable links in TMP, it works perfectly, except on one of the links it for some reason highlights the very first character in TMP (not even close to the link):
[RequireComponent(typeof(TextMeshProUGUI))]
public class TextMeshLinks : MonoBehaviour, IPointerClickHandler
{
[System.Serializable]
public class LinkClickEvent : UnityEvent<string>
{
}
private int link;
private TextMeshProUGUI textMesh;
[SerializeField]
private Color32 highlightColor = new Color32(0xC8, 0x27, 0xB4, 0xFF);
[SerializeField]
private Color32 linkColor = new Color32(0x4E, 0xDB, 0xFF, 0xFF);
[SerializeField]
private LinkClickEvent linkClicked;
private void Awake()
{
textMesh = gameObject.GetComponent<TextMeshProUGUI>();
textMesh.ForceMeshUpdate();
}
private void Start()
{
if (linkClicked == null)
linkClicked = new LinkClickEvent();
}
private void OnEnable()
{
link = -1;
}
private void LateUpdate()
{
if (textMesh.isActiveAndEnabled)
{
int curLink = TMP_TextUtilities.FindIntersectingLink(textMesh, mousePosition, Camera.main);
if (curLink == link)
return;
if (link >= 0)
LinkHighlight(textMesh.textInfo.linkInfo[link], false);
link = curLink;
if (link >= 0)
LinkHighlight(textMesh.textInfo.linkInfo[link], true);
textMesh.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
} else {
link = -1;
}
}
private void LinkHighlight(TMP_LinkInfo linkInfo, bool hover)
{
var textMesh = linkInfo.textComponent;
int s = linkInfo.linkTextfirstCharacterIndex;
int e = linkInfo.linkTextLength + s;
DebugConsole.log($"link position: {s} {e}", this);
var color = linkColor;
if (hover)
color = highlightColor;
for (int i = s; i < e; i++)
{
// Get the index of the material / sub text object used by this character.
int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;
// Get a reference to the vertex color
var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;
vertexColors[vertexIndex + 0] = color;
vertexColors[vertexIndex + 1] = color;
vertexColors[vertexIndex + 2] = color;
vertexColors[vertexIndex + 3] = color;
}
}
void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
int link = TMP_TextUtilities.FindIntersectingLink(textMesh, eventData.pressPosition, Camera.main);
if (link < 0)
return;
var linkInfo = textMesh.textInfo.linkInfo[link];
var linkId = linkInfo.GetLinkID();
linkClicked?.Invoke(linkId);
}
}
the start and end character in linkinfo are correct
it seems like this code breaks when link text includes whitespace
How to post !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.
I did inline code block, this is a pretty small code block? just a single small component
Large Code Blocks
The fact that it takes 2.5 screen heights is probably a no, small code blocks are like 15-20 lines
well it's small to me, it easily fits into discord message and this doesn't say how much is "large"; is there any actually useful advice
Yes, using a paste website
It's better in all ways because it also has line numbers, which is useful if you have a stack trace or something that points to a line
there is no stack trace or anything, code works perfectly, it just highlights first character in TMP when text inside <link> tags includes whitespace
Its about stuff like people can go "On line <n> you did this, but then on line <x> y ou did that, you want to add <this> to line <y>"
also try and take the time to cut down your code to only the parts that matter, can just stick a ... to replace the chunks that arent relevant
like when I see stuff like DebugConsole.log($"link position: {s} {e}", this); in your code you want help with, that makes it harder to parse and isolate out "what part of this code do I gotta be actually looking at"
well the part that breaks is right after it but that part is literally just copy from TMP examples (the working one because examples included the ones that didn't work at all as well)
for (int i = s; i < e; i++)
{
// Get the index of the material / sub text object used by this character.
int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;
// Get a reference to the vertex color
var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;
vertexColors[vertexIndex + 0] = color;
vertexColors[vertexIndex + 1] = color;
vertexColors[vertexIndex + 2] = color;
vertexColors[vertexIndex + 3] = color;
}
this is the relevant part (since s and e are correct)
anyway, I figured out the fix myself
or at least not a fix
but workaround
for (int i = s; i < e; i++)
{
if (!textMesh.textInfo.characterInfo[i].isVisible) continue;
int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;
var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;
vertexColors[vertexIndex + 0] = color;
vertexColors[vertexIndex + 1] = color;
vertexColors[vertexIndex + 2] = color;
vertexColors[vertexIndex + 3] = color;
}
this is workaround
How to use a public function in a static public function?
You need a reference to an instance of the type
How do I do that?
You can't call public functions from a static function without some instance of the class first
Singleton, new instance, theres plenty of ways
Function in a function? You can't access local functions from outside the method that declares it
Assuming you have something like the following
public void A()
{
// other code...
void B() { }
}
B can only be called from inside A
No
I have:
{
isCheck = false;
SimQueen(1, 0, x, y);
SimQueen(0, 1, x, y);
SimQueen(1, 1, x, y);
SimQueen(-1, 0, x, y);
SimQueen(0, -1, x, y);
SimQueen(-1, -1, x, y);
SimQueen(-1, 1, x, y);
SimQueen(1, -1, x, y);
return isCheck;
}
{
NewBehaviourScript sc = controller.GetComponent<NewBehaviourScript>();
int x = xPiece + xInc;
int y = yPiece + yInc;
while (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y) == null)
{
x += xInc;
y += yInc;
}
if (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y).GetComponent<Chess>().player != player)
{
if (sc.GetPosition(x, y).name == "black_queen" || sc.GetPosition(x, y).name == "white_queen" || sc.GetPosition(x, y).name == "black_bishop" || sc.GetPosition(x, y).name == "white_bishop")
{
Debug.Log("Jauc");
isCheck= true;
}
if ((sc.GetPosition(x, y).name == "black_pawn" || sc.GetPosition(x, y).name == "white_pawn") && x==xPiece+xInc && y==yPiece+yInc)
{
Debug.Log("Jauc Pijun");
isCheck = true;
}
}
Ah yeah, so you need a reference to an instance of whatever class this is in, to be able to call it from the static method.
Though why is the method static in the first place, is it for easy access?
It's not the right way though, what if you somehow need two of whatever script this is in the scene?
You're better off not making anything static at all, and let the script that called CheckIfPieceIsAtk() take in a reference to an instance of that script
[SerializeField] private TheScript _script; // drag-drop in the Inspector
void Start()
{
_script.CheckIfPieceIsAtk(42, 69);
}
Should I put that in the other script?
The script that used the static method before
Is unity officially support VScode ?
don't crosspost
But i didn't get the answer
doesn't mean you can crosspost, also was barely 2 mins..
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
read the bottom message
emoji on your post says No btw
which is true
I can't drag and drop. It is a prefab not in the scene?
Thanks man
Okay ok man , why you are so rude , take easy , thanks
You're supposed to drag-drop an object in the scene that has the script attached, into that "Script" field it made in the Inspector
it's ok to be corrected , don't take it personal 🙂
The object that I want to run the script on is generated using code not in the scene
Okay, so you need whatever object that Instantiates it, to pass the script for you
GameObject clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().Script = _script;
why not just spawn it as SomeScript and avoid the GetComponent
But I don't want to create it?
Well, how would you be able to reference it then? If there's no instance of it anywhere, you can't call a method on it
Static did you bad it seems, taking shortcuts thus not learning how to reference properly
See https://unity.huh.how/programming/references for a quick intro
Thanks
what is sc in this case
its fine to have static methods if all the way down the chain they are "glass box" methods that dont need to access stuff outside of them that isnt also static
but it looks like your method there shouldnt be static and should be on the Queen or whatever instead
when your method name has a thing name in it, thats usually a code smell, like in your case instead of SimQueen(...) perhaps it should be Queen.Sim(...)?
Hello, in order to read a json with a dictionary composed of english words and their meanings, i have this code https://hatebin.com/dwjnkhstgj that and an example of the json file: {
"word1": "meaning1",
"word2": "meaning2",
"word3": "meaning3"
}
and i get the following error: object reference not set to an instance of an object on line 37 with the foreach. anyone know how to read a json file into a class with dynamic properties?
resolving JSON with a dynamic object is not supported in Unity, at least without a 3rd-party plugin.
What you must do is create an object identical to the JSON object,
or parse the JSON text itself.
Question: How is the JSON created?
the json was obtained from a dictionary, this is the original file i was trying to read for a game with words and their meanings
I don't believe that is technically valid JSON.
Perhaps in some sense. But it looks like a Key-Value pair type of thing, which is typical for a dictionary.
Perhaps it is a dictionary object. But I don't know how one would resolve that from JSON into a Dictionary in C# 🤔
Either way, a simple fix is to simply parse all the key-value pairs from the raw text file.
It would involve writing code that knows when it is inside/outside "quotation marks", and whether the current text is a key or a value.
Actually, instead of making a custom object, try to just make it a Dictionary<string,string>
making it a dictionary<string,string> was one of the things i tried but to no avail unfortunately
would probably be easier to create something like a javascript program to convert the json into a more suitable format and use it then
What precisely went wrong?
i believe it was the same error
could you share that method in a pastebin link? https://gdl.space
Task.Delay() doesn't work in unity right?
it was the same error as the code i sent above here: https://hatebin.com/dwjnkhstgj
all lead to that no matter what i did
Should work.
ill just use coroutines
public static IEnumerator ShakeObject(this GameObject gameObject, float HowMuch, int HowMany)
{
for (int i = 0; i < HowMuch; i++)
{
var off = Random.onUnitSphere * HowMuch;
gameObject.transform.position += off;
yield return new WaitForSeconds(0.5f);
gameObject.transform.position -= off;
}
}
This look allright?
Dictionaries are not serializable by unity JsonUtility. You could use the newtonsoft package for that.
unity when you make a for(;;) loop:
"This little manouver is going to cost us 51 years"
infinite loop?
yeah
huh what does unity have to do with it ?
you have HowMuch instead of HowMany on for loop
that's a bug (?)
thank you
np 🙂
Hey guys, I'm trying to do some maths to figure out projectile trajectories, but my smooth brain is not helping.
I want to shoot a straight projectile so that it collides with a straight moving target. They're both moving at different but constant speeds.
This is happening on a 2d plane.
What I have:
- projectile speed
- projectile initial position
- target speed
- target position
What I need to discover: - projectile direction
You'll probably need to calculate how long the projectile will take to reach the targets initial position, then calculate the targets predicted location within this time. Then point towards the predicted location
Although clearly the time to reach the predicted location wont be the same as the initial location, but this can be ignored if you are able to apply more/less force to make up for this
this is possible to do algebraically and I've seen it before but my brain is too smooth to set up the equation atm
Yeah, smoothness has taken over here too
But I'm starting to think that it can't be done under the circumstances
I dont think a general solution exists, since there are cases where your projectile will never catch the target based on speed
it deifnitely can be
I actually don't have the projectile speed
yes this would be apparent in the algebra
It's based on the projectile direction, which is what I'm trying to find out
you'd end up with a system of equations with no real number solutions (only complex solutions)
to do this algebraically and get a unique answer the speed OR the direction needs to be fixed
If you had the equation you could just set them equal to each other, to see where they meet
if both variables are free, there will be many possible solutions
Yeah, that's the problem right now
I thought that I had the speed, but I only have the multiplier
what is "the multiplier"
It's a spaceship that fires projectiles according to this formula:
LinearVelocity + worldDirection * ProjectileSpeed
ProjectileSpeed is a float, the other two are vectors
that's confusing
I understand worldDirection * ProjectileSpeed but then what the heck is LinearVelocity
Are you fine with cases where the output is just "not possible"?
Yeah, totally possible
It's the spaceship current velocity
so then you do know the speed
in fact, the full velocity of the projectile
No, the full velocity is dependent on the worldDirection, which is what I need to find out
yes but
it''s all fully defined
it's not an unknown
there's a function for it
that can be plugged into the math
(which I remain too smoothbrained for still 😉 )
This is better since you have the vector and the direction its gonna move, rather than just the velocity as a number
Although, now im curious as to why the direction even exists, since the goal is to calculate your own
@eager tundra step one is first work out the formula for calculating the intersection point of the 2 vectors for the two traveling objects.
Then the formula for time it takes em both to get to that point t1 and t2
Then just solve for t1 = t2
A bit more context might help here, It's something like an aimbot
Like an unfair AI
I can fire in any direction, but I want to fire in a direction that it will always hit, if the velocity allows
That's a lot of "just calculate it" lol
Are u allowed to adjust the velocity of the projectile?
No, just fire and forget
Like not even the initial fire speed?
Nothing, just the direction that it'll be fired
It's totally fine if it doesn't hit
I would probably go with what I initially said then
So, I've tried something like it, but I got stuck because I can't find the velocity since it's based on the direction
This
That actually looks pretty interesting, let me give it a try
Well it would be pretty inaccurate depending on if the target is moving fast tbh
I too am being smooth brained, but I'm out so cant really look up the formula that im forgetting
What praetor said with systems of equations can work too
So to start you can calculate for a given specific angle, with velocity constant, if it will or won't hit
Then work backwards from there to "reverse engineer" the angle
you need to boil it down to an angle that you plug into the formula
you may also need to solve this piecewise (per axis)
CommandInvokationFailure: Failed to update Android SDK package list.
C:\Users\visha\AppData\Local\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat --list
Can anyone help me with this error , Im tryin to build my AR app and this is happening
i followed steps from Youtube and stackoverflow but it's not working
if i do ScriptableObject ojb = new ScriptableObject(); will it create a new file?
Hello, can i set the size of the graph view manually without using the function graphView.StretchToParentSize() ? Thank you
If you did that you would have an invalid object, because that's not how you create an instance of an SO.
CreateInstance doesn't create a file either though.
I’m looking to check if a specific function has been added to a UnityEvent, is a string comparison using GetPersistentMethodName inside a loop of the added events the best course of action or is there a way to directly compare functions
If you really need to do that then you should deal with GetPersistentMethodName. However your question sounds like a XY problem.
Why do you need to "check if a specific function has been added to a UnityEvent"?
Oh I'm doing some absolutely cursed stuff dw haha. I have two separate systems that can link up but also i'm trying to go heavy into observer pattern stuff so if System A needs System B that connection happens through a UnityEvent, then I want to add the relevant listeners
It's probably an over engineered idea but I'm a game designer who's still learning programming so I wanna make it as designer friendly as possible while trying to keep it optimized
each system shouldnt really have to worry about other listeners
I don't understand this response, Could you please elaborate?
Im guessing your sort of angling towards a Pub/Sub model, and you want to save time by not bothering to publish stuff to your pipeline that has zero subscribers?
like in the observer pattern, you can think of your code as reacting (by calling your function) when something happens (the event is invoked). Each observer shouldnt really worry about other observers, as in you might be doing something wrong if you have to decide to observe based on if someone else is
though its hard to really specify, since everything said so far is high level. itd be easier to help if you said what this system was actually for
The terminology is new to me but the latter half sounds about right yeah.
@lean sail Apologies, I'll explain the practical use one moment
Pub/Sub as in Publish Subscriber 🙂
The two systems are my Interaction system, and my new Inventory system
The Interaction system is a super generic prefab+script that handles a majority of the interactions in my game. Checks if the player is in range and looking at the object and then if the Player holds down the interaction key it does a timer and then finishes. All of this is changable in the inspector and I use UnityEvent's to allow for designers etc. to chuck in whatever they want to happen on an Interaction completion or failure.
The Inventory system is a way to store different types of things the Player might have using ScriptableObjects, the most relevant type of item I use is a Pickup.
I want these two systems to be as abstracted as possible but with the ability for them to link, a practical example would be the player obtaining a Keycard Pickup, Then using that to open a door via an Interaction
The other major example that prompted my initial question is that an Interaction can give the player a Pickup, for example that Keycard would use an Interaction. The players ability to do that Interaction can change depending on the type of Pickup, ie. if the player can only hold 1 Keycard then I need to lock the Interaction if the player has that Pickup. I want to do this by checking if the Interaction is trying to provide a Pickup in it's completion event, then tell that Interaction to listen to if the PickupInventory happens to change
I am so sorry for that worddump of explanation 😭
I think comparing method strings might end up being the best way to handle this without adding anything new to the Interaction inspector (which realistically is probably the right answer but im being stubborn and wanna streamline it as much as possible)
Gotcha aight so, what I would do is instead break up all your Interaction logic into 2 pieces each.
Interaction + ValidateInteraction
Hi, I was wanting a joint to rotate freely (using a CharacterJoint at the moment), for instance the rigidbody the joint is connected to is constantly spinning, I want the joint to just act as a joint and not break or have a limit on how much the gameobject can twist etc before it spazzes out.
Thanks in advance
first you check the ValidateInteraction which returns some form of ValidationResult thing, that then informs you as to whether you even bother calling Interaction
hinge joint should be fine, or configurable joint if you want more settings. If you dont want them to break then the default value already should just be infinity
Ah ok, thanks 🙂
how do make it so that one field is shown in inspector just when another boolean is true?
custom inspector, isn't it?
custom inspector, naughty attributes also has an attribute for that if you don't want to write the custom inspector/attribute for it yourself
I didn't get part with attribute, have you said that I need to write attribute myself?
like i said, you can write it yourself. or you can use naughty attributes
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
You don't have to use Attribute but it would be most generic.
"ShowIfAttribute cannot be found"
did you install naughty attributes?
no.
well obviously it won't work if you didn't install the package
does is make sense to import everything from asset?
also, I have installed naughty attributes, but I still get error
also there is no NaughtyAttributes namespace
Okay I need help. I want to download already compressed Images instead of doing it on the runtime. But this code me returns Debug.LogWarning($"Error while downloading resource < {url} >, error: Download result was null");
How should I approach downloading already compressed images?
Do you guys have any idea, how I can implement this type of movement into my 2d game? In Tutorials it is only shown how to move forward and backward, but I wanna move also to the side like shown here because I think it gives the game more depth
Do you have an idea how I can manage this?
character is just moved with x and y axis
implement WASD movement first
How can I do that
what script do u have yet
I just followed the Brackey tutorial for 2d player movement
Let’s give our player some moves!
● Check out Skillshare: https://skl.sh/brackeys7
● Character Controller: https://bit.ly/2MQAkmu
● Download the Project: https://bit.ly/2KPx7pX
● Get the Assets: https://bit.ly/2KOkwjt
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·································································...
if u know how to move in x axis u should be able to make the move to y it's the same thing
How to stop executing script when throwing custom exception?
if (smthIsBad)
{
Debug.LogException(blabla);
StopExecutingScript();
}
or does script stop executing itself when exception is thrown?
Like an actual Exception?
try catch
If you have error pause enabled, unity will pause the whole game when an exception is thrown. If you only want a specific script to stop, you’ll have to try catch it and handle the exception yourself.
oh, I see, I can just
if (smthIsBad)
{
Debug.LogException(blabla);
this.enabled = false;
}
thank you
https pastie io rdxxoh cs
wait, I can just
throw new InvalidOperationException();
hi everyone
Hello, I'm trying to update an old project that was using Unet to netcode.
The old code is using the class Unity.Networking.MessageBase but it doesn't exist in Netcode and I can't find in Google how to update this, do you have an idea to help me ? Thanks in advance
probably not the correct approach to just expect to change type names + variable names and have it compile 😛 changing from a networking API to another will most likely require architecture changes
Not exactly code but I've made a game where you have different levels in unity but the levels are pretty similar and all use the same prefabs. is it better to have each level as it's own scene or one scene that places the level you want in the game as a prefab, so each level is it's own prefab. or is there some better way to manage these levels?
separate scene per level is last resort, so anything else is a better way 😛
Better to use addressables 😄 and control your loading in more nicely matter. In that case you will save quite a lot of memory and it wont matter much if it different scenes or different prefabs. It is easier to use subsenes as you can more easily load unload stuff.
but thinking back on it, it might not always be the case*. I was thinking levels like Super Meat Boy for example, in which case it'd be a drag..
what are subsenses and addressables?
no it's 3d stealth game so mostly it's some props, enemies and walls
for stuff like Fable where the levels can be detailed and big, a scene per 'level' is best
I understand, is this the correct documentation to what i'm trying to do ?
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
Example of code I need to update to Netcode :
public class Hook : MessageBase
{
public int to;
public int from;
}
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
I don't know :/
I'm not sure what you mean by addressables and subsenes 😄
seems like it yes
Addressables is Unity package. https://docs.unity3d.com/Manual/com.unity.addressables.html
Which help you to control what is loaded and not loaded to memory. So if you planning or thinking how to implement stuff, I would suggest study this package and when you will finish you will have straight plan for loading unloading levels, stages and etc.
netcode has its own serializer?
alright I'll be studying it then. thank you
yeah
i updated MessageBase like this but i don't know if i'm correct
public class Hook : INetworkSerializable
{
public int to;
public int from;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref to);
serializer.SerializeValue(ref from);
}
}
Before :
public class Hook : MessageBase
{
public int to;
public int from;
}
i guess? seems like it
This will let u use it as a network variable or in a rpc I believe, if that was the goal
hm?
rephrase the question
ok sorry
i have an array of gameObjects, and i want to call a function in half of them
but that half has to be selected randomly
so if you have array of 10 elements
you want to either do that function on 0-4 or 5-9 indexes?
or randomly as in random half elements from X index
easiest approach is to first shuffle/randomize the collecton, and then simply take the amount you need
more or less, it whould be a random between 1-10, the thing is idk the number of elments that the array will have
shuffle it and select X elements you want from the array making sure it's not out of it's length
public static IList<T> Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = UnityEngine.Random.Range(0, n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
you can adapt it for an array
i will try it
but list is preferable in your case
Using a list would probably be easier then, so u dont have to worry about unused elements
you can do it with void asewll
public static void Shuffle<T>(this IList<T> collection)
{
int n = collection.Count;
while (n > 1)
{
n--;
int k = UnityEngine.Random.Range(0, n + 1);
T value = collection[k];
collection[k] = collection[n];
collection[n] = value;
}
}
hmmm, i didnt use lists very much, but i will give them a try
the return is done so extension calls can be chained
oh, yeah learn lists
while at it learn also Stack/Queue/HashSet/Dictionary
invest time into learning fundamental collection types
okay, thanks :)
You should not cross-post.
I want to make my text black with Outline, but because of the language I use, the words are written stuck together, the texts are in this way
you can adjust spacing between character in TMP settings
With this, Fonta will be uncoordinated
And again, the outline is determined between the characters
Oof. I just got tangled up reading about ScriptableSingletons (editor only unfortunately), asset bundles, and addressables and now I no longer know what to do. What is the recommended way to store global settings or configuration variables? Values that do not change during gameplay or values that might be constants that are only changed between new builds of a game. I want to get rid of magic numbers (and public const int variables at the tops of my scripts) and move all of that into "Debug Configuration" and "Asset Import Configuration" ScriptableObjects so I can stop hunting for magic strings in my code if I need to change something. My gut instinct is to stick my scriptable objects into the Resources directory and create a singleton "SettingsManager" class through which I can access the variables in my configuration. Should I not do that? People online just parrot "Singletons bad" and "Resources folder bad".
A core feature for me would be not having to assign any references in my components or editor windows, hence why I'm thinking of using a singleton.
nothing wrong with singletons
Does anyone know by any chance if yielding the same instance of WaitForSeconds is supported?
WaitForSeconds sleepTime = new WaitForSeconds(1F);
while (true) {
// ...
yield return sleepTime;
}
yes
C# side seems to just store how long to wait, not sure how the native side stores the elapsed time and if each evaluation starts the counter over
Cool, thanks
An SO is probably how I would do it. Easily editable, single asset for source control.
Actually, that is how I'm doing it (lol) for a project I'm on.
Hi, does this server have a code review channel?
or an appropriate place I can submit my code for a community review?
An SO for config variables is nice and easy. makes great for testing and setting game/world values . . .
We don't, no. You can post in one of the coding channels if you want.
boowomp
Yup I got that, I'm more concerned about how to load and access it. I'm currently putting all of my configuration SOs into their own addressable group and loading that in a singleton. I guess that is the cleanest solution?
yeah, you're just storing a yield instruction instance. you can even — get fancy — make your own . . .
Hey guys, having a if in update is that ok ?
i mean it can mess up with performance no ?
the if i want in my update is that
if(player.HP <= 0)
{
state = BattleState.TURNTWO;
}
ok see 🙂 thx
you are looking for branchless programming, but you may end up with a much slower code, you have to test it
eh, not really branchless here
probably more event-driven
i.e. you do this check when you change the player's HP
does having a object rigidbody that is static will not be available to a OnCollisionEnter2D detection?
Yes great idea, i'm on it, check when HP change
Rigidbody event is called between the 2 colliders
static has 0 to do with it
Hey, I'm getting a really weird bug, where my scripts aren't able to get variables from a scriptableobject until I open said scriptableobject in the inspector (no errors). I think it might have something to do with how I load/save the scriptableobject.
I have a "bank" that stores references to my scriptable objects using string id's, so to save/load scriptableobjects I just store the string id, and use it again to find the scriptableobject using the bank.
Here's the code for loading:
for (int i = 0; i < data.restaurantData.activeMainCourseItems.Count; i++)
{
foreach (KeyValuePair<string, ScriptableObject> keyValuePair in DataPersistenceManager.instance.prefabManager.prefabBank.scriptableObjectBank)
{
if(keyValuePair.Key == data.restaurantData.activeMainCourseItems[i])
{
FoodItemSO itemToAdd = (FoodItemSO)keyValuePair.Value;
mainCourseItems.Add(itemToAdd);
}
}
}
The input action manager's input UI doesn't position the top part correctly, is there a way to fix this?
what "arent able to get variables" means?
null ref? default values?
it just returns null
it shouldn't be an issue with the dictionary, as it works for other cases
it's able to get the scriptableobject itself, just not the variables from it for some reason
nvm solved it, it was an issue with naughtyattributes.
does anyone knows why cant i move contents inside my scroll view
probably because it is being controlled by some layout group
Hey, I get the error "Coroutine continue failure" from this code ;
if (currentBubbleCoroutine != null)
{
StopCoroutine(currentBubbleCoroutine);
yield return null;
}
if (GameOptionsMenu.instance.language == Language.English)
{
currentBubbleCoroutine = StartCoroutine(CombatDialogue(buckAI.dialogueBuck[6]));
}```
How do I stop the previous call to a coroutine before starting the next one?
you clear the coroutine anywhere?
What do you mean by clearing?
you start a coroutine, you store it in a variable
coroutine stops, you check for null, its still there
variable still references dead coroutine
Oh I thought it would become null as it ended
no, it doesnt inherit Unity.Object
So the error comes from stopping a finished coroutine?
im not sure what the error means, ive never encountered it, is there any additional info in the error?
Absolutely none
Which makes it hard to tackle
I'll try setting the coroutine back to null after stopping it
Thanks for the help
Btw, is there a way to do what I did inside the coroutine?
That would be handy, but I think I can only assign the coroutine as I start it
I guess I can wrap everything in a method
oh
i think i understand what the error means
im not sure how its possible for unity to detect this case, but
is the code above the code of the same coroutine that you start/stop?
Sorry I don't understand what you mean
currentBubbleCoroutine
CombatDialogue then
so what happens, you send a coroutine to execute, it reaches the null check, it stops
at this point the coroutine is removed from unity coroutine manager and MoveNext() will not be called on it
but you still yield a null instruction after that
which means you yield into nothing, which probably is what produced that error
try yield break and see if the error is gone
Do you mean the yield return null after the StopCoroutine in the code I posted?
yes
Cos that was just a test, I was wondering if waiting for a frame would solve the problem
you cant wait a frame for a coroutine that is already stopped
it is removed from enumeration, it wont be called again
The coroutine from the code I posted is not the coroutine I'm calling
why did you post it
Cos I'm suspecting the error coming from the way I handle the variable
The Coroutine variable
public void CallCoroutineCombatDialogue(string text)
{
if(currentBubbleCoroutine != null)
{
StopCoroutine(currentBubbleCoroutine);
currentBubbleCoroutine = null;
}
currentBubbleCoroutine = StartCoroutine(CombatDialogue(text));
}```
I get the behaviour I expected doing that
Probably needed to make the variable null again before reassigning it
Thanks for the help
you mean the error is gone?
add yield return null; after currentBubbleCoroutine = null;
right
Cos the coroutine made a dialogue bubble fade after a certain time, so if I were to call the coroutine before the previous one finished, the dialogue would fade too early
Dunno how clear that is. Anyway, seems to work, I'm not gonna ponder on that :p Thanks for the help
Which is better a cooldown using Courutines or a cooldown using Invoke?
even tho, is like Invoke any efficiency wise better than courutines or vice-versa?
used for cooldown puropuses ofc
My personal preference is neither, just a countdown in Update
A countdown in Update means you can extend/shorten it, adjust the speed of the cooldown or straight up cancel it very easily.
eh id not to have many scripts use update at all , unless you had a global update
I only have 1 global one any other scripts can tap into
Unity's recommendation
multiple scripts with Update methods are bad
but how many would you say can be used given the standard 16ms frame budget?
like whats the threshold?
which tests did you run?
idk
Minimize.code.that.runs.every.frame.
Consider whether code must run every frame . Move unnecessary logic out of Update, LateUpdate, and FixedUpdate . These event functions are convenient places to put code that must update every frame, while extracting any logic that does not need to update with that frequency . Whenever possible, only execute logic when things change .
If you do need to use Update, consider running the code every n frames . This is one way to apply time slicing, a common technique of distributing a heavy workload across multiple frames . In this example, we run the ExampleExpensiveFunction once every three frames:
yeah i know all that
I'm just parroting unity , I did not personally test this. Just follow the goat
i was asking a concrete thing, what is the point where you decide that the overhead of update is bigger than the overhead from maintaining your own update manager
i wonder if it can be tied to frame budget?
like if you are bottlenecked by raw update overhead i would consider porting it to custom update dispatcher
probably hooked into playerloop
This kind of authoritative statement isn't useful. While it's true that there's a small cost to using lots of Update calls versus one object calling lots of Updates, you'll need hundreds of objects in the scene before this adds up to really be worth addressing. Just avoiding Update period because of this sort of performance thing is premature optimization.
will need a base class for all your game comps, or interface and boilerplate code in OnEnable/Disable
That said, shameless self plug: https://github.com/DameonL/MonoInjection
some very optimized fast intert/remove collection to keep track of them
I never said avoid Update period though lol
i exagerrated the amount probably, you probably do need over (1k assuming) update scripts maybe dent some
lock?
Just use the library I provided if you're worried about the performance impact at all, or it can at least show how to do that sort of thing
probably one day I can be big brain and just use ECS completly 🤞
maybe you have the answer to the question?
Which question?
what is the point where you decide that the overhead of update is bigger than the overhead from maintaining your own update manager
good ?
Best way to tell is using the profiler, and the math involved depends on the Update management system you use, since different mitigation systems can have different performance impacts when you're at that kind of micro-optimization level. For example, my system uses an Interface, and calling an Interface method is slightly slower than calling a class method
I'm just wondering back to the original question,
would it probably be less garbage to have a script just for Timer in Update or make Coroutine when needed with the timer tracked in there
that's what sparked this in the first place
There's no hard and fast way to tell when; if you expect to have 100+ objects with Update in a scene, an Update management system is probably a good call, otherwise if you suspect a bottleneck profile it and address it
alright ill run the numbers im really curious
You can do Coroutines in a way that doesn't generate garbage, so either way can be 0 garbage
coroutine is still slower and its not dynamic
the optimal way to solve this is to create a Timer class and use it classes that require some internal timer for something
you can extend the timer to have modifiers, scales whatever
Somebody did the math on the cost of Update calls at some point on the Unity forums, but I can't find it
what about if you turn timer into a Job 😈
hi, how do I check bool in WaitForSeconds
what does it mean?
you don't?
yield returning a WaitForSeconds tell unity to wait for that many seconds
if you want to wait for a condition to be true, consider WaitUntil
they probably mean smth else
yield return new WaitUntil(() => boolean);
this is my AI enemy script: https://gdl.space/emuyahapiv.cpp
I'm trying to play a jump scare when the enemy reaches a certain distance away from my player. The idea of the jumpscare is that the agent stops and the jumpscare animation plays, but my player also stops (by disabling his playermovement script) and I force him to look at the enemy. The player also takes 25 damage. I want the jump scare to stop after 5 seconds and have the enemy move back away from the player after its done. With the way my code is now after 5 seconds my player is still frozen and the enemy wont move away from the player. Also, the player keeps taking 25 damage rather than just taking it once.
so the difference is about 2x, 50k unity updates use 10ms, direct ~5.2, interface ~5.2, virtuals ~5.2 on my machine in release mode
so about 3ms unity update per 10k objects
hm i still wonder, a game with 10k updating components would probably not be something trivial
Interesting that your test didn't show any difference between interface calls, I know there has been a minor difference in the past
i know there is theoretical difference
since its sort of virtual, afaik it goes through vtable? i dont know clr that well
case UpdateType.Interface:
foreach (var item in _interface)
((IUpdate)item).InterfaceUpdate();
it means how do I use a inumerator to turn a boolean on when it's off instead of using a float timer and float counter
do you mean setting boolean to true when coroutine has finished?
major difference compared to list iteration, but obviously that cant be used, i wonder if fast array would work here
how do you type that?
You want us to write your code for you?
probably.
can I speak
I don't understand formulation though
is it general question?
yeah with fast array its down to ~2.6
i meant how do you write that code so that it doesn't break in half because i my code is as stable as paper clips and gum
Write the code, and then ask us about the issues in the code
IEnumerator Bla()
{
while (bar)
{
yield return null;
}
foo = true;
}
When having scuff marks when dragging something or making tire drags etc, is it better to do it via the particle system or by decals?
thanks for that
I don't think that was that hard to implement yourself
so ok assuming average game has the upper limit of about 3k updating components, then the difference between unity update and the fast one would be around 0.5ms
I am new to programming and I have little cofidence in myself to not get a 1000 new errors
who are you speaking with ?.
with you
The only way you fix that is to get 1000 new errors, and learn to fix them
Every error is a learning opportunity
I should be Einstein by now
really? what did this dialogue start? 🙄
no not really
ok then. I'll let you know how that goes in #💻┃code-beginner
why?
just write in #💻┃code-beginner if you're a beginner
OnBecameInvisible doesn't seem to be detecting correctly
note that the scene camera also counts
and it won't become invisible if the scene camera is watching it
oh
even if im not on the scene tab?
Possibly? not 100% sure
int NearLights = gameObject.GetNearObjectsWithTag("Lights", 20, out NearestLight);
fancy line of code
pointless line of code without the extension method that sits behind it
My character seems lagging when camera follows the player.How can i fix it
how is your player moving and how is the camera moving?
charpos2 = mCharaTop.transform.position;
charpos3 = charpos2 - charpos1;
cam.transform.Translate(charpos3);
this is camera
mCharaTop.transform.Translate(Vector2.left * speedMultiplier * Time.deltaTime);
this is player
i tried many ways to move camera but all of them lagged
quick question is it possible to get the normals of the collision while using OnTriggerEnter2D?
I don't really need physics so I'm not using any rigidbodies except for one
So is it possible to retrieve the normals from a collider2d that is returned by the ontriggerenter
no
you can do workarounds
like raycasting from the object's previous position or something