#archived-code-general
1 messages · Page 238 of 1
that il forget about within a few weeks lol
because I saw one online but the person who uploaded it to YT didnt provide a link to play it
Thanks! This seems promising for generating C# documentation https://www.jetbrains.com/writerside/
mesh manipulation is indeed not a beginner topic @near sail
aww rip
you should probably learn how to make an actual mesh before destroying one or cutting one..
also there is Sebastian Lague on YT
https://www.youtube.com/c/SebastianLague
look him up
got a question, i am trying to turn a vector3 from world space to be mirrored on a canvas UI in overlay mode, using the search engines give me terrible results, How is this process called and/or how can I achieve it?
i basically want to render an image on top of an object and make the image follow it
there a many different types of mesh
World Space to ViewPort, World Space to Screen Coordinates
Viewing frustum to Screen Coordinates?
you mean turn it to Vector2?
Vector3 = 3D space, Vector2 = 2D space
they just mean convert from the worldspace coordinate system (with the center of the world as 0,0,0 and going positive and negative) to screenspace coordinates (with 0,0 on the bottom left and going only positive up to the resolution values)
to a Rect Transform
you can also find the code for Vector2 in ChatGPT or online code libraries like github or stackflow etc
Rect Transform is just a component.
But Mao gave you the answer
https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
Edit: oh, mao was asking for clarification.
Well world to screen should do it
based on your use
code varies signaficantly, use library or chatbots for help based on what you need
This aint working either, it interprets it like i was trying to put a 2d pos into 3d space
you can put 2d pos into 3d space
Ah, right it's on the camera. I was looking to see if transform method had it
or matrix4x4
will look into this later
i recommend you to open a new test project and implement that specific function
so you can test freely
it does it through the viewing frustum because it's just a point so that makes sense
otherwise you'd need a transform
Actually you could just do it with the camera matrix and make a matrix4x3 with the point
I forget
dw i have it ready
i have an array of objects and i want them to have images on top lol
i just dont know how the effect is called
generally used to tell you to pick up an object and stuff like that
i'll see what i can do with that function, thanks
Aethenosity is on the money on what to do so read into that method
you are saying you want to anchor a screen space UGUI element to a 3d scene element?
yes
i will be honest, this is shockingly complicated in Unity, because of UGUI
not because of the math
guess i'll have to search in older projects, i had a function that did this but can't find anything that explains it tho
do you use a canvas scaler?
not sure what it is, it just uses the screen size
anyway, use this https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
set the localPosition of the rectTransform to ( the screen point to the local point in the recttransform's parent), multiplied by the canvas scale factor
it's hard
strange that i have Time delta time yet my mouse movement get slower with increased frame rate
Mouse input should not be multiplied by DeltaTime
It's already framerate independent
I didn't need to use that, this was all I had to do
okay learned something new, thanks guys
When i press play my camera is being teleported away from the player, how could i fix this?
i also get a ton of these errors even though Mouse X is setup
MouseX isn't a thing
it's telling you MouseX isn't a thing
To fix the name it looks like
Mouse X
https://docs.unity3d.com/ScriptReference/Input.html
Edit: ah, that link doesn't list it
perhaps it wanted you to look inside Input class for the proper name 🙂
ok i fixed that so there are no more error messages and i can use my camera, but it still teleports away from the player on start
as for the camera problem, hard to know without knowing more about the scripts
or how is it that camera is moving in the first place
heres the scripts themselves
Remove deltaTime from the mouse input first of all
i would just put camera holder as child of player
only rotate player to rotate camera on Y
ok
try to keep it on Pivot mode, not Center
Sometimes it throws you off for precision
I naïvely thought I could make an AssetReference field on a class, then use that field to directly reference an AudioClip I had dragged into that field.
But I'm getting an error in the IDE *Cannot implicitly convert type 'UnityEngine.AddressableAssets.AssetReference' to 'UnityEngine.AudioClip' *
Anyone know a quick/easy way to achieve my objective using AssetReference (or other easy method). Thanks!
Anyone know a quick/easy way to achieve my objective using AssetReference (or other easy method)
what is your objective?
Eh now I kinda regret asking this lol. Because I guess I could just use an AudioClip reference directly on my SO. I can't remember why I thought AssetReference was the way to go anymore.
Basically I wanna make a list of all my built-in audio assets along with a unique ID to reference them by.
So I made a SO that has a field for AudioClip and a unique GUID string.
if (g != null && g.garmentObject)
{
Destroy(g.garmentObject);
}
if g.garmentObject is a class rather than a bool, what does referencing it this way mean in the context of an if statement?
Normally it'd be an implicit null check
what could it be otherwise?
im snooping out a big-ass error that causes the entire editor to crash, so I'm stamping out any possible dodgy code
Infinite loop would cause the editor to crash, not a null reference exception
That likely isn't your issue. If the crash is related to objects being destroyed, check their destructor (dispose, on disable, on destroy, etc)
yeah probably
A good way to see if this is an factor is to comment out the destroy call
but I want to make sure I know exactly what the above code could be doing
I know it's because of the destroy call because of breakpoints
but the code is such a mess that I want to make sure if this might be contributing to some other kind of error
The break point would simply occur before the crash. Did you step through to the very line before the crash?
I didn't make it and it's both very complicated and very poorly documented
no I'm still figuring it out
i think that the code might occur in an OnDestroy() function on a script that happens to be on the object being destroyed
Comment out Destroy and see if any crashes are occurring
You can substitute with inactive objects temporarily for the test if those objects need to be removed from the game
does someone know why my player is being slippery when moving? i tried increasing my drag but that didnt do anything
sorry if im just being stupid lol
AddForce is just kinda slippery
But what did you set groundDrag to?
What's wrong here?
void OnDisable()
{
Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
string out = "";
foreach (Vector3 vertex in mesh.vertices)
{
out += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
}
for (int i = 0; i < mesh.triangles.length(); i++)
{
out += "f " + mesh.triangles[i] + " " + mesh.triangles[i+1] + " " + mesh.triangles[i+2] + "\n";
}
print(out);
}
And you mean you did this in the script?
What about physics materials? Have you set friction?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
im following a tutorial, so no friction yet
Show the whole script !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
I would look it up and try it
ok
that was basically the whole script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class geoExporter : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void OnDisable()
{
Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
string out = "";
foreach (Vector3 vertex in mesh.vertices)
{
out += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
}
for (int i = 0; i < mesh.triangles.length(); i++)
{
out += "f " + mesh.triangles[i] + " " + mesh.triangles[i+1] + " " + mesh.triangles[i+2] + "\n";
}
print(out);
}
}
out is reserved keyword as navarone says
and getcomponent can take a generic parameter, also consider using string builder
also, do not call mesh.triangles inside of a for loop
good point
cache it to an array before using it anywhere in the for loop or else it will repeatedly reallocate an entire array every time it's called
well, looks like I crashed unity
I was hoping to see line numbers in a paste site haha, but the others got it resolved I think
Oh
huh, turns out unity doesn't like it when you print a crazy ammount of text at the end of runtime, whoda thought
well, maybe unity just doesn't like me
I bet it's not as simple as that. Seeing how you go about constructing a huge ass string and accessing mesh vertices, there's so much opportunity for something to explode.
well my end goal is to export it to a .obj file
If you gonna do it, it should probably not be in OnDisable
I'd also note that you're iterating the triangle array incorrectly, it should be +=3
yeah, it executes on the 30th frame now
so you currently have 2x the amount of triangles listed
Same way as in C# generally
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class geoExporter : MonoBehaviour
{
int frame = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
if (frame == 30){
Mesh mesh = ((MeshFilter)gameObject.GetComponent("MeshFilter")).mesh;
using (StreamWriter outputFile = new StreamWriter("output.obj"))
{
Vector3[] vertices = mesh.vertices;
foreach (Vector3 vertex in vertices)
{
outputFile.WriteLine("v " + vertex.x + " " + vertex.y + " " + vertex.z);
}
int[] triangles = mesh.triangles;
for (int i = 0; i < triangles.Length; i+=3)
{
outputFile.WriteLine("f " + triangles[i] + " " + triangles[i+1] + " " + triangles[i+2]);
}
print(vertices.Length);
print(triangles.Length);
}
}
frame ++;
}
}
this makes a file correctly, but its all zeros
Use the debugger to step through the code
also how is it possible that the number of vertices is equal to the number of triangles?
You could have more triangles than vertices, more vertices than triangles, or an equal number of each
yes, but it's incredibly unlikely for them to be equal (I'm doing marching cubes)
triangles.Length is actually 3X the number of triangles
if you never reuse any vertices
and every vertex is used in a triangle
you'll have exactly that 3:1 ratio of vertices to triangles
and triangles.Length == vertices.Length will be true
now I just have to figure out how I have 393216 vertices, with all of them displaying just fine, yet the triangle and vertex lists are filled with zeros
well, it isn't zeros, but it's not better lol
Hello, I'm having an issue with bullet trails. The bullet gets destroyed when it hits something obviously and there is a trail attached to the bullet. The bullet uses a rigidbody. I also keep the trail alive after its parent, the bullet, gets destroyed (by simply unparenting it). My issue is that if the bullet hits something right in front of the shooter, the trail does not appear. If the target is far away, the trail appears correctly. I'm not sure how it works, but I'm guessing the bullet gets destroyed before the trail can even start? The bullet has a speed of 200 which makes it quite fast. How could I fix that?
Here is a video showing the issue
just spawn the trail at same time as the bullet and use a raycast to get its length
Ok, I'll give it a shot, thanks
Help, I don't understand this error. Anyone seen it before and can help?
Just a variant on an IndexOutOfRangeException
https://unity.huh.how/runtime-exceptions/indexoutofrangeexception
Can't tell you anything more without the stack trace or code
ok @quartz folio I'll dm u the code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh sorry
do you not want me to dm?
if (EnemyList.Count > 0)
{
DistanceXandY(gameObject.transform.position.x, gameObject.transform.position.y, EnemyList[0].Troop.transform.position.x, EnemyList[0].Troop.transform.position.y);
distanceClosest = distance;
distanceDirectClosest = DistanceDirect(distanceClosest);
foreach (EnemyTypes enemy in EnemyList)
{
DistanceXandY(gameObject.transform.position.x, gameObject.transform.position.y, enemy.Troop.transform.position.x, enemy.Troop.transform.position.y);
distanceDirectCompare = DistanceDirect(distance);
//If out of checked so far closest is further than new one, then get that enemy
if (distanceDirectClosest > distanceDirectCompare)
{
closestEnemyNumber = enemyNumber;
}
enemyNumber++;
}
closestEnemy = EnemyList[closestEnemyNumber];
ratioX = 1 / ((distanceClosest.x + distanceClosest.y) / distanceClosest.x); //5, 10 ratio : 15/5 = 3
ratioY = 1 / ((distanceClosest.x + distanceClosest.y) / distanceClosest.y);
if (hasUpdateBeenCalled == false)
{
velocity = new Vector2(ratioX * 100, ratioY * 100);
//velocity = new Vector2(0, -10);
hasUpdateBeenCalled = true;
}
/*
shootAngle = Mathf.Asin(closestEnemy.Troop.transform.position.y / closestEnemy.Troop.transform.position.x);
myVector = Quaternion.Euler(0f, 0f, shootAngle) * myVector;
gameObject.transform.Rotate(0,0, myVector);
*/
}
}
#📖┃code-of-conduct
Don't think I do, no. lol
Presumably closestEnemyNumber is out of range of the list when you do EnemyList[closestEnemyNumber]
yeah very sorry
but would need the stack trace and line numbers to know
So I have 2 goals around my player 2d colliders... feet need to have actual friction for movement to feel correct and body needs low friction maybe even a small amount of bounce to prevent air movement from allowing players to push themselves against walls.
My initial soln was to have two colliders covering the relevant space with different physics materials but I think thats causing relability issues in my other collision response components where a quick enter/exit or a multi enter/exit from these multiple colliders is breaking the assumptions.
So I could harden all my trigger reaction stuff against this but I'm wondering if people here might be have a suggestion for some other soln to the original problem that would let me keep trigger reactions dead-simple
What is the best way to replace a sprite sheet with a new one? Because when I do that I have to setup all item sprites again after adding one icon. Is there a way to do this without setting up sprites again?
what is this thing that moves my player when i move it?
What "thing"?
How come it’s not like On my player
You can see in the inspector and the hierarchy
Oh I thought they were 2 separate things
It is. It's your visuals that are offsetted it seems.
You can always see what's selected in the inspector and the hierarchy.
Ya know, it makes a lot of sense now why all my raycasts weren’t working
So im getting this error, i dont know what its referring to at all, any help?
The first one, the other two wouldnt exist without the first one
These are generally Editor errors thrown by IMGUI after a domain reload. Not anything you can do something about
so i cant fix this? not even completely reinstalling anything or anything
nope, just clear the console and they should go away
yea, but it fails my upload for the game because of the error
you mean your build?
yea, it wont work with that error there
That looks like it is Editor only code so should not even be in a build. You might be better asking in the VRC server
yeah, im trying there too, its just that this error is so unique compared to my other errors that i dont know exactly what is causing it
I've created a bootstrap scene for my game to manage the order of initializations for singletons, etc.
Can anyone recommend a workflow/workaround for this approach to load this stuff first when running an arbitrary scene in the editor?
Do you have an Editor window open which has anything to do with VRC?
nothing other than the sdk's splash screen.
screenshot
Do you not read what is on your screen?
ive tried that already......same error
error is there still
not the "getting the control...." but same, this is a vrc error at this point so im jumping servers.......
you could probably make some menu item load your bootstrap scene then your current scene additively
yes, null/empty content-type header in http request is definitely a bug in the VRC sdk
this seems like a good approach, thanks for the suggestion! 
Does anyone know if there's a builtin Decompose method for float4x4? i.e. one that extracts the translation rotation and scale
Not all 4x4 matrices are valid transformations, so that’s not quite possible. But you could apply it to a vector of your choice to get out whatever you want via builtin vector ‘comparisons’.
Hello everyone;
My project's artist has come up with a clever way to save time for himself by having material variants have different parent declinations.
We tried having a simple scrit that reparents a one single Material used by every characters and this only works in Editor because you can't change parent property in a Release Build.
I'm not too familiar with this pipeline and materials, is this somehing that can be done, or are we approaching the problem the wrong way please? Thanks
Usually if you're modifying materials at runtime you're creating a new material instance. Lot of the variant batching is at compile time for what I've read and it does kinda make sense, but I've not read too much into it.
It probably creates its own additional source code for variants is my assumptions
Trying to use visual scripting for enemy AI logic by using it as a flowchart to control which voids to use in my actual script.
How do I get it to use public voids from a C# script
*I know there is a specific server for visual scripting but I'm not getting a response
Methods? I don't use VScripting but it seems like you're looking at a different script of attributes there.
no, its the same script
I could only suggest looking how a method(?) like Set Attacking is configured, otherwise may be wise to try out some tutorials since is probably very basic enough to find that info
I've read that documentation but it never talks about Scripting and Build runtime, always only editor, hence my question
I know nothing about VS. But, you are using the GetVariable object, which would suggest it works on Variables not on Methods
I'm wondering if this can work with MaterialPropertyBlock 🤔
Hello
I’m making a system of requirements for a gun (required reload time, required damage, required gun magazine size)
More experienced ones, please tell me how to do this adequately, so that I have all the requirements stored, in principle, in one list, how to organize an adequate abstraction, because now I can’t come up adequately and it turns out that I can come up with the maximum on the screen
that is, I would like to conveniently get the parameter I need by type to compare the required type
if the type requested type.MagazineSize then it would pull int, and if reloadTime then float
the essence is the following
there is a service from which I can get the current gun stats
and there are requirements to pass the level
I need to compare them and update my UI
How can I launch a dedicated server build from MacOS terminal
Can't even launch it, "open executableFileName" doesn't work.
The executable is correct, double clicking it works.
Need to launch it with arguments.
excuse me, I heard there is a better way to do this:
if (rigRadio != null) rigRadio.SetRigStatus(false);
What is it?
running a function only if the object is not null. without using if (something!=null)
I have a question reguarding the reading and writing of data to mass amounts of gameobjects:
In my scene, I have 1024 total tiles (these are gameobjects instantiated by a script that just loops over the X and Y axis), lets say I want a tile with ID 7 to have a set amount of stone, but tile ID 8 should have a set amount of oil, and so on so forth.
What would be the proper way to do this without much overhead?
Say if there was an extraction building, that had to collect the stone from the tile, how could it read the data from said tile?
you should have a eg tile manager, then ask the manager to return that tile for you
Ideally not a separate GameObject for each one.
Tile Data can be in an array e.g. TileData[,] or Dictionary<Vector2Int, TileData>
Quick question. My editor (VS Code) grays out something and tells me "Name can be simplified". Will that pose any problems, or is it a suggestion on how to make my code cleaner? Relevant Snippets:
You don't need the generic type specifier with this TryGetComponentInParent call
The type can be implied from your parameter
Same for when you call your custom function
the only problem here would potentially be from that result is not null which might return true if the component you are getting has actually been destroyed and is therefore == null but not really null
that was actually your code @leaden ice
or in the editor where GetComponent allocates for unity's fake null when no component is found
Oh sorry I'm actually just a little delirious on flu medicine
But in your first screenshot you can remove the <StatsHandler>
It's not my code that can be simplified but yours 😜
when I do that, it throws an error:
Oh
ik 😛
Uhhhhh ok back to delirium
can you show what it looks like now with the generic type parameter removed? because you should be able to do that
if that's what you meant
you've removed the out parameter, that is required
you need the whole parameter. is it just the generic type parameter (<StatsHandler>) that can be removed
oh... That's what I did here
No
Be mindful, if someone requests your code as text, don't send a screenshot!
nvm, I found what I goofed:
// goof
if (collider.gameObject.TryGetComponentInParent<>(out enemyStats))
// fix
if (collider.gameObject.TryGetComponentInParent(out enemyStats))```
I sent screenshots because it was easier to show the message, sorry
screenshots make it more difficult for everyone helping you though. especially those first couple where discord only shows part of them so it can shove them all inline in the same message
yeah, makes sense now in hindsight. I just wanted to show the message mostly
now it's fixed. Although would there be a problem if I didn't remove the <StatsHandler> part?
nope, the compiler just infers it from the type of variable you pass as the out param so its just more verbose with it included
hey everyone, I want some help with an issue that I have been facing while making a chess game, the chess board is made up of a rows array, the rows array is a game object array, and the pieces are not a child of the chess board object but child of a different object, now i do not know how do i ensure that when a piece is selected it highlights the legal spaces that it can move to, such that a piece which is already occupying a space, this space shouldn't get highlighted
ideally your array should contain the type that you actually care about rather than just GameObject. but you would just check your array when determining what are legal spaces and if a piece occupies that space in the array then you know it isn't a legal move
umm i am a bit confused here
"but you would just check your array" which array are you talking about?
the one containing your pieces
ahh, no, currently there is no array that stores the pieces, all the pieces are just child of a game object
this is want i meant
ideally your array should contain the type that you actually care about rather than just GameObject
as in, make an array for your pieces
the array represents spaces on the board. you put pieces in the index that represents their current position on the board
here is the chessboard, the Row child are rows of the chessboard and their child are tiles of a chess board
Is there a clear and concise place to see how Unity Lobby events work? The documentation and Youtube videos ive found barely help at all.
For instance, how do i actually access the data in this:
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You should look into using 2d array for grid based games and abstract a grid space class.
It probably would help if you just asked your question.
Sure ill say it rn
The game manager has a problem
On game over
The problem is when the player restart the game the variables get missing
Let me change it
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public GameObject gameOverUI;
public TextMeshProUGUI restartCountdownText;
public PlayerShooting playerShot;
public FPSController fpsController;
public PauseController pause;
private float initialCountdownTime = 10f;
private float currentCountdownTime;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
private void Start()
{
}
public void GameOver()
{
gameOverUI.SetActive(true);
Time.timeScale = 0;
playerShot.enabled = false;
Cursor.visible = true;
pause.enabled = false;
if (fpsController != null)
{
fpsController.enabled = false;
}
currentCountdownTime = initialCountdownTime;
StartCoroutine(RestartCountdown());
}
private IEnumerator RestartCountdown()
{
while (currentCountdownTime > 0)
{
restartCountdownText.text = Mathf.CeilToInt(currentCountdownTime).ToString();
yield return null;
currentCountdownTime -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
currentCountdownTime -= 1;
}
}
RestartGame();
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1;
playerShot.enabled = true;
Cursor.visible = false;
pause.enabled = true;
if (fpsController != null)
{
fpsController.enabled = true;
}
restartCountdownText.text = "";
}
}
because you reload the scene, those objects that your singleton is referencing are destroyed. and since it is DDOL it is not destroyed. so when the scene loads you need to get references to the new instances of those objects
Hey 👋 Updating our project from unity 2021 to 2022 made it so one folder specifically is suddenly not compiled within the project. Any references to its contents throw a compilation error. Anyone encounter anything similar?
That's was really helpful thank you
yes, thank you for the advice
Is there an assembly definition in it?
What folder is it?
Hello everybody, I'm having issue with creating a bullet pool.
Here is a show case of the problem
No pooling here, my bullets do go where I want
And here is when I enable pooling. It seems like the data of the pooled reused bullets are not correctly overwritten
Here is the code from my rifle spawning the bullet:
public void Shoot(RaycastHit hit)
{
//Preventing shooting while weapon on cooldown
if (cooldown > 0) return;
Vector3 aimDir = (hit.point - bulletSpawner.position).normalized;
BulletProjectile bp;
if (Weapons.instance.bulletsInPools[bulletPoolIndex].Count > 0 && Weapons.usePooling)
{
bp = Weapons.instance.bulletsInPools[bulletPoolIndex][0];
Weapons.instance.bulletsInPools[bulletPoolIndex].RemoveAt(0);
}
else
{
bp = Instantiate(bullet, bulletSpawner.position, Quaternion.identity);
bp.name = owner.weapon.name + " Bullet " + Weapons.bulletIndex;
Weapons.bulletIndex++;
}
bp.Setup(owner, bulletSpawner.position, bulletSpawner.position + aimDir * range, aimDir, speed, bulletPoolIndex);
cooldown = Time.time + 1 / fireRate;
//Debug.Break();
}
And here is the bullet code:
public void Setup(PlayerController player, Vector3 start, Vector3 end, Vector3 aimDir, float speed, int bulletPoolIndex)
{
gameObject.SetActive(true);
bullet.SetActive(true);
this.bulletPoolIndex = bulletPoolIndex;
owner = player;
startPosition = start;
transform.parent = null;
transform.SetPositionAndRotation(start, Quaternion.LookRotation(aimDir, Vector3.up));
targetPosition = end;
float distance = Vector3.Distance(startPosition, targetPosition);
float timeAlive = distance / speed;
timeToDie = Time.time + timeAlive;
rb.AddForce(aimDir * speed, ForceMode.VelocityChange);
TeamColor();
}
private void Update()
{
if (timeToDie <= Time.time)
Explode(false, Hits.Ground);
}
private void Explode(bool hitSomething, Hits hit)
{
if (hitSomething || explodeOnNoHit)
{
ParticleSystem prefab = groundHit;
if (hit == Hits.Soldier)
prefab = playerHit;
ParticleSystem ps = Instantiate(prefab, transform.position, Quaternion.identity);
//Change color to team color
if (hit == Hits.Soldier)
{
ParticleSystem.MainModule psm = ps.main;
psm.startColor = Config.TeamColor(owner.Team);
}
ps.transform.LookAt(startPosition);
}
rb.velocity = Vector3.zero;
bullet.SetActive(false);
Invoke(nameof(Pooling), trail.time);
}
private void Pooling()
{
if (Weapons.usePooling)
{
transform.parent = Weapons.instance.bulletPools[bulletPoolIndex];
Weapons.instance.bulletsInPools[bulletPoolIndex].Add(this);
gameObject.SetActive(false);
//Debug.Break();
}
else
{
Destroy(gameObject);
}
}
(Sorry for the huge code, not sure if it's ok to post all that :x)
Anyway, when I reuse the bullets from the pool, it appears the direction of the bullet does not get properly overwritten and still flies toward its previous path?
Would anybody know what's causing the problem?
I forgot to mention I'm using Unity PlayerInputManager to allow split screen so I have up to 4 players. Currently, both players are linked to my mouse and shooting at the same time for easier testing.
But I'm assuming split screen shouldn't impact pooling logic anyway.
the videos seem showing the correct result, the bullet from red guy and green guy fly to different directions
I cant really get what are the differences, and i wonder how your pool looks like
in Setup you are adding force but you are not removing any residual force/velocity from the previous usage
i see the velocity is resetted in Explode
Oh, I thought rb.velocity = Vector3.zero; would disable the force
What do I need to do then?
I think you need to do that just before you add the new force
because you use ForceMode.VelocityChange
In the second video, if you look at the bullets from green soldier, the bullet don't fly toward where I'm aiming. Sometimes, they fly toward a previous spot I think. Sometimes, a bullet from green soldier will even target the spot shot by red soldier.
I'll look into it. I'm not familiar with Unity Physics and just followed a basic bullet tutorial where they don't really explain how it works.
VelocityChange is not really meant for the situation in which you are using it so you might want to experiment with the other ForceModes as well
the VelocityChange force mode adds the first argument to the velocity of the rigidbody directly, with no other calculations
it's equivalent to just adding to the rigidbody's velocity
except that it will be applied in the next physics update, rather than immediately
Force and Acceleration are for steady forces. Impulse and VelocityChange are for instant changes.
Force and Impulse care about mass. Acceleration and VelocityChange ignore mass.
But even so, velocity only affects the speed of the bullet. It should affect the angle.
In my second test, bullets just flies to random previous target. Even though I change the aim direction of the pooled bullet in Setup
This is the confusing part.
But since I set velocity to Vector3.zero in Explode, the VelocityChange in the next Setup will simply reset the bullet to its usual speed, shouldn't it ? From my video, the speed of the bullet is fine. Only the angle is wrong.
No, it's just a normal folder named "UiImage". Renaming it to anything else fixes the issue somehow, lmao.
perhaps you need to clear the velocity when you fire the bullet, not when it hits something, as Steve said
the speed you use is a constant so that should not change. you set the velocity using direction and speed
I'm unsure how rigidbodies behave when their gameobject gets deactivated and activated like that.
exactly^
You could always log the velocity when you fire to check if it's zero or not.
also, resetting velocity is not everything...there's also angularVelocity, notably
I can't say if that's relevant here
Oh indeed. I forgot direction is a component of velocity. I'll give it a shot.
Ok, using kinematic true then false did reset the velocity. VEctor3.zero did not.
Just before adding force]
But now, I have another issue
In my weapon Shoot, I'm supposed to take the first bullet in the pool and remove it from the pool.
But somehow, and only somtimes, both player use the same bullet when I click.
Meaning that sometimes, randomly, bullets are not fired at all for one of the soldier.
I'm not sure how it's possible. Shouldn't the Shoot method triggers one after the other when players shoot?
I need some help with code for reflecting and multipling objects
So Im trying to make it so that when a projectile hits a certain collider, itll make a duplicate projectile that shoots off at a slightly different angle
But I cant seem to make it so calculate the new trajectory of the new projectile
private void multiplyBullets(Vector2 originalDirection, GameObject bullet)
{
bullet.GetComponent<BaseBulletBehavior>().isMultiplied = true;
int bulletMultiplier = PlayerManager.GetInstance().bulletMultiplier;
Rigidbody2D baseRb= bullet.GetComponent<Rigidbody2D>();
float baseRotation = baseRb.transform.rotation.eulerAngles.z;
float offset = 2f;
for (int i = 0; i < bulletMultiplier; i++)
{
float newRotation;
if (i % 2 == 0)
{
newRotation = baseRotation + offset;
}
else
{
newRotation = baseRotation - offset;
}
Vector3 eulerRotation = new Vector3(0f, 0f, newRotation);
Quaternion rotationQuaternion = Quaternion.Euler(eulerRotation);
GameObject childbullet = Instantiate(bullet, transform.position, rotationQuaternion);
Rigidbody2D childRb = childbullet.GetComponent<Rigidbody2D>();
Vector2 spreadAngle = Quaternion.Euler(0f, 0f, newRotation) * Vector2.up;
childRb.velocity = spreadAngle * bullet.GetComponent<BaseBulletBehavior>().bulletSpeed;
childbullet.transform.right = spreadAngle;
}
}
Atm im using smth like this
But after testing it it definitely because the rotation that is obtained is before it is reflected by the colldier so the new projectiles jsut break as it doesnt get reflected
So im trying to find a way to obtain the new trajectory once the projectile bounces off
how do I go about doing that
Not seeing any normal calculations
Basically you grab the contact points when you collide and create a vector from the normals
Or are you having trouble with instantiating new bullets here because they are too close to the collision?
So the bullets would not collide with one another just with the collider
So I dont think spawning them too close would be that much of an issue
Is there a function to get contact points?
OnCollisionEnter(Collision collision)
If you're using collision, I'm not sure if trigger colliders work though
The collision parameter has a property with the contact points
damn im using triggers rn
guys can i use C++ in unity
Ill check
So i think it does by using clostspoint()
But how do I check the new trajectory afterward
yeah doesn't seem like trigger colliders have them
not easily
It only supports C#?
directly supports, yes
[not sure what the best channel to ask is]
so i work at a company that does games adjacent stuff. interactive education and training sorts of things, especially in the life sciences. Our tools and workflows look like game dev all up and down.
my boss is lately pushing real hard to get everybody at the company to adopt AI into our workflows, and take advantage of the emerging tech sooner rather than later.
as a programmer, i ask chat gpt to throw together some boilerplate code every now and then when i'm using a tool i'm not familiar with, or when the task is relatively simple. But that's by far the minority of the work i end up doing, and it rapidly gets less useful and less accurate as the request gets more complicated. it's not even possible to ask gpt for help once there's more than one script involved.
is anyone here actually using AI tools routinely in their workflow?
I'd love to just shrug and ignore this, but this push for AI workflows isn't going away and i'm sure I could appease my boss if i had just one robust example to talk about.
Just get Copilot and call it done
Beyond that, as you said, beyond basic things there's nothing ChatGPT is going to be speed up
You can do closestpointonbounds, but may want to look around for a more accurate way. The reason why contact points are nice is because you can get an average of points so you can make an average normalized vector from that. I guess you can raycast a bunch when you collide as well around the surface.
depends how accurate you want to be with ricocheting
Actually, if it's just a bullet then it's probably fine. Not like there's much surface area to it all.
Is there any C++ engine rather than UE5 my pc struggles to run that
I like this one
https://flaxengine.com/
oh thanks so much
since when did godot start using C++ dosent it use its own language?
probably to "extend features"
godot also uses C#
ah i see
is it easy to use C++ in godot?
or do i use flaxengine
no idea
thanks for your time
flax seems more intergrated with C++ so go with that or UE
Am doing something wrong?, why cant you iterate through Lobby Changes? I am having so much more trouble with Unity netcode than with photon.
it's probably not a List/Collection
try add .Value
PlayerJoined.value?
Thank you! Is there an easy way for me to inspect these classes in VS to see that I have to add 'value' next time?
whenever you mouse over pretty much anything in VS it will tell you what type it is
best bet if you see a case like this, add a . and see what intellisense suggests
or just read the docs
Thank you both
How do i do the same effect of GetKey in the new input system with a composite value, up, down, left, right setup in the action map, i want to be able to keep moving my player while holding down the button but it only triggers once
new input system is less about continous callbacks / polling and more about subscribing and unsubscribing
perhaps there's been more methods of input since I last check, but ideally you'd subscribe on first input and unsubscribe when you let go of the input
not too sure how analog support works with it though
yea, i am using invoke unity events behaviour in the new input system so i did subscribe/unsubscribed the methods, everything works beside the continuous trigger effect
also #🖱️┃input-system for future reference cause input system can be somewhat confusing
on performed -> set a vector2 to the input value
In an update method use that vector2 to move the player
on canceled -> set the vector2 to zero
so i would have to use the update method inevitably then? i was trying to avoid using it but if not possible i guess will do that thanks
If you want something to happen every frame, you need it. Or you can make a coroutine with a while loop that yields a frame, but... then you're just recreating Update
Movement will want to happen every frame (well, generally physics frame using FixedUpdate) to make it smooth
The input system is about handling input, not driving all of the code running in your game
if you need something done every frame (such as moving), Update is still the natural place for that.
Alright, thanks for all the answers
is there some better way to have methods get called in sync with animations aside from using animation events? I feel like using a bunch of animation events to call various methods is not a good idea, is this really the best practice?
is there any way to have the script like call an animation and method if the animation finishes without using an animation event?
There's also StateMachineBehaviour
But what do you have against animation events?
StateMachineBehaviour is the way to go as stated by someone else.
I just feel like relying on a death animation to finish before destroying the game object will lead to issues in the future
and great, is this the best practice for animations and timing this accordingly like game logic? I get like using the animation to change the sprite red for damage makes sense as being controlled in the animation events, but game logic like shooting a bullet seems a bit tough to manage if its controlled by an animation
Using Animation Event is correct. Simply make sure that the animation cannot be interrupt or if gets interrupt you are not in an invalid state.
The easiest way is to control the animation 100% through your own statemachine.
cool thanks
so if I had a death animation lets say that ended by calling a method to destroy the game object, would the best practice be to just add the logic in the script (like cantwalk, remove collider, cant attack) while we are waiting for the game object to be destoryed, just so that animation won't be interrupted? @steady moat
If you are in the DeathState, the DeathState controller the animator. Nobody can hijack the DeathState. If you consider that there is a possibility that someone hijack the DeathState, you can simply use the Any for all your transition and you will almost be sure to never be in an invalid state.
At that start of each state (In your code - Death, Idle, Attack), you switch to the appropriate Animator State.
right, I need to learn more about using state machine behaviors, thanks a lot for the help
hjelp 😔 /j
With what?
Also, is this a code question?
not nessesarily, is there a channel for funnies?
No. There is no offtopic whatsoever
let’s say a bomb explostion is going to push someone in a 2D sidescroller. the direction of the force should probably be locked to 8 directions? or 4?
Why lock it ?
consistency
Not sure what makes it consistent
so if player throws or triggers a bomb, and it’s a bit off, the angle of whatever gets pushed effectively gets rounded to the same direction
More like a question of design, but I do not think it makes thing more consistent.
I'm expecting object to get push in the inverse of direction from where the explosion is.
the challenge here is mostly when everything is going fast, and the distance is very small, so the angle is very sensitive to small differences
is your movement system actually locked in 8 directions?
no
if you aren't moving on a grid i dont think that makes sense
objects in the world spawn in a cartesian grid tho
it may feel off for the player, but not really a question of code
You can make the algorithm more robust to those little change without locking the direction.
so initial positions for all the objects is locked to a grid, but then things can freely move
so are you snapping the player to the grind at all time, like a chess piece that must be on the 0,0 of a square ?
no, but some blocks in the world are snapped to grid
maybe continue in #archived-game-design since it isn’t a coding question
If we are really talking about really, really small change, then you might look into Numerical stability to see if there is anything that you can do to fix your algorithm.
How to load and autoimport package from server?
I have server with several .unitypackage files. I want to load this files from server and then import this files to my project.
if I use OnRenderImage to render using compute shaders, is there any way to have this happen before postprocessing so I can apply postprocessing to it, or is there a way better than onrenderimage that works? unity 2021 builtin
just make your own NPM server no?
what part of this do you have a problem with? It's actually very simple
You can create a post processing effect that executes early in the stack
do you guys think 20~ish seconds to load a 100x100 tile stage is taking too long for a modern computer?
I need it to run off a monobehavior script
You could add a CommandBuffer with the compute dispatches on the camera on CameraEvent.BeforeImageEffects.
whats the best practice for giving a player an ability from a set of like 100 abilities, is it to make a gameobject with the script and instantiate it as a child or is it to hold the information somewhere as a variable like playerAbility1 = swordswing?
oooo ok!
If it's a basic 2D tilemap game, then yes.
any suggestions on fixing this? currently I'm loading from json (level editor saves to json), each tile stores 3 game object (every layer has a tile that has 2 images (base tile + animated sprite)
at present I'm instantiating the game objects when loading, should I
a) divide into chunks and load the player first
b) do a whole loading entirely
c) something idk
oh i'm also spawning about 1000 enemies
and a bunch of gameplay objects like breakables, treasures, etc
to be clear the actual game isn't that crazy, this is a stress test, but I'm perplexed that its taking 20 seconds to load
Howdy. I am working on custom editor stuff and have run into the issue of not being able to add an enum to the custom editor script. I have tried a couple variations I found online but I cant seem to get anything that works. Here is the line I am using
levelController.startingLvl = EditorGUILayout.EnumFlagsField("First Shed Door Close Trigger :", levelController.startingLvl, typeof(Enum), true);
levelController is the script I am making the editor for
startingLvl is the enum
Does anyone have a solution?
Totally missed that channel. Ty
Hey guys, I'm building a unity game for ios and embedding it in a react-native project.
I'm trying to make my dev flow as automated as possible, I'm wondering about two things:
-
is it necessary to rebuild the Unity project to an XCode project each time I make changes to the scene/scripts
aka is it necessary to do the following each time: File -> Build Settings -> Build -> Select folder -> Append the build -
If it is necessary to do the above each time my scripts/scene change, can I automate the process to build the XCode project from the command line? I'd rather invoke a script than to go through all these menus
The first thing you always have to do when faced with performance issues is to profile it. Unless you know what's taking so long, you can't fix it.
don't spam the channel. there's no off topic here #📖┃code-of-conduct
so reading the json takes about 8 seconds, loading tiles takes about 5 seconds, monsters are pretty fast, I changed some stuff and its about 13~15 seconds now.
So I tried preloading the json into a grid while running the previous level, but it takes way too long (currently putting it in a coroutine running in the background to load)
so I guess the main question now is, how do I cut down on time taken to read the json
Depends entirely on how you code ability and the system that uses abilities. Are the abilities chosen at runtime? You could add them as components to a certain object
easy, dont use json
what's a better solution? I'm making a game where players can make their own levels, so I'll need to store it somewhere
binary serialization
thanks, I'll look into it
Does anyone know why my unity package icons arent showing up?
things work still and function. just the icons wont work for any unity items, i can change them to other things like 7-zip, etc. But they wont change to unity
that's not a code question. and it's likely because your OS hasn't been told what to use to open those files
what do you mean 'icons wont work'? Icons are just pretty little pictures and have no function whatsoever
icons for anything unity dont show up visually, and i was just wondering if there was a fix to it, but i'll find it
This is not a code problem.
i know thats why im jumping out............
oh, my bad, i missed box's reply
What happens to my UI code when I build for dedicated server? for example a listener to a button, that wont be needed on my server, is that still running on the server and wasting resources?
Just a heads up. Don't cross-post . . .
abilities are chosen throughout playtime, roguelike style: level compete pick an ability, I am not sure what is the best practice for this, i assumed scriptable object, but am not sure
You probably need to first think more about how you want this working gameplay wise. For example if the player has only 4 abilities at one time, you need some way for it to choose which ability to overwrite. If they can take as many as they want, you need some way to use a variable amount of abilities. Then you can design code for how to use abilities. Once you make code to use abilities, then you can pick abilities whether that overwrites or adds to your current ones.
I think having it as a monobehaviour is fine honestly, let's you use unity inspector more even if you dont need the unity functions.
My game works fine in the editor, but when I go to build it im getting the error "The type or namespace "SceneAsset" could not be found". I have assembly files for each of my scenes, but my Level manager has drag and drop SceneAsset references. I have using UnityEngine; and declare it as public SceneAsset scene; And it works in editor play. Can I not use SceneAsset in a build?
Scene asset is editor only iirc
You can use a string from the scene asset, and surround the scene asset stuff in a conditional
The entire UnityEditor namespace cannot be used in build. Scripts that use this namespace are normally placed in "Editor" folders that are not compiled into the build.
You mean unity editor?
Yes. my bad.
I use this as a replacement. https://discussions.unity.com/t/inspector-field-for-scene-asset/40763/5
I have an array of "Levels" that I drop the scene level.unity file onto. So I just have to change that to load by name or something?
It lets you drop in a Scene asset and then get its name at runtime
Thanks for the help, Yeah basically seeming like the player will have a set of 4 abilities that can be swapped out, and no other information has to be loaded about them. I was going to do a mono behaviour that just takes button input and converts them to which ability script should be used based on a list of the 4 abilities a player has. Any better way to do this?
This is an example how unity ngo does it.
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/using-networkscenemanager/#basic-scene-loading-example
This is what I mean to do, the section in OnValidate
Okay thanks for the help. Thats a shame this is editor only
Right now I have something kinda similar. Basically I have an array that stores 4 AbilityBase and then my input handler has 4 methods, 1 for each ability. I just manually call [0],[1] etc
I think the easiest way to do this is to just make each ability a MonoBehaviour
then you can make a prefab for each ability and drag the ones you want onto the player
Sometimes I try to make things POCO but it's so much nicer being able to drag instances around lol
yeah
(plain old C# object)
I sometimes use [SerializeReference] to serialize plain old objects, but I often wind up needing unity objects anyway
e.g. I want to be able to assign a reference to the ability somewhere
so are we getting the ability script through the game object thats attached to the player? or do we run the script from the list of 100 or whatever abilities in the game like player pressed Q, so we call ability 27 to run?
I would give the player a list of Ability
where Ability is an abstract class deriving from MonoBehaviour
anything in that list can be activated
I'd make a game object to hold each component and parent them to the player somewhere
Not every game object needs to correspond to a tangible "thing"
yeah
I have a whole hierarchy of "non-things" in my game
game globals -> managers -> [many objects holding singleton components]
you can quite literally just cast primitives to/from bytes. It's extremely fast if you don't need any form of compression
That is pretty much what I do right now, it does somewhat get awkward if enemies though are not limited to 4 and you have to change the system
interesting, very helpful hearing your info about this thanks a lot
making super-generic controls is hard
In that case, I'd separate the player/AI control from the actual character
the player control component would use four input actions to activate each ability; AI would just pick randomly from the entire list, or whatever
I'm almost at 100 abilities lol
how do you have it structured?
thank god for reusability
Basically just scriptable objects, but if you don't want the project bloat then serialize reference work too
new Ability<AbilitySO> then cache myself a particle pool
interesting
one problem with using generics like that -- you can no longer have a List<Ability>
since Ability by itself isn't a valid type
interfaces ;)
serializing interface types is annoying
honestly, I could do without, but I feel like it makes sense to always had a SO coupling contraint to each class that requires a data asset
I personally like using sub classes, it lets each individual ability have its own code for animations, behaviour, data tracking etc, and you can use them interchangably since they all share a main class
It's actually worse than that
public interface IBaseAbility<out SO> : IStorable<SO> where SO : IBaseAbilitySO { }
public abstract class BaseAbility<SO> : Storable<SO>, IBaseAbility<SO> where SO : IBaseAbilitySO
long story
is there a decent workaround for not being able to assign Vector2 or Color with default argument values?
or do I just need to make a whole new overload?
just make an overload without that parameter that just calls the other overload and passes your desired default value
public void SomeMethod(Color whatever)
{
//do work
}
public void SomeMethod() => SomeMethod(Color.white);
Can someone tell me if this is a unity bug? Why would selecting them cause their enum values to be set to 0?
` public class SoundData : MonoBehaviour
{
public AudioSource AudioSource;
public SoundId SoundId;
}
public enum SoundId
{
Unknown = 0,
Bounce = 10,
Bounce2 = 11,
Jump = 20,
Dash = 30,
AnnouncerReady = 40
}`
It's a enum editor thing
I think it's just how it's serialized was it? But try keeping the values orderly.
Hi. I'm making a charging enemy that has to hit mulitple targets. they seam to hit the player more then 10 times. is there anyway way to limit it once?
Depends how you want to do it, such as giving a player some invincibility frames, or making it so that specific enemy can't damage the player again (in a short span of time?)
the enemy can't damage the player after their charge attack is done
If it's enemy specific then you should add an internal flag to that enemy such as hasAttacked or something similar which you will check as they try to continously damage the player
i tried that. that what currentTarget is supposed to do but it ignores it because it repeats that void over and over again
Oh I see. Do you have multiple player's in your game here?
funny thing is, I just put in a bool and it worked
trying to understand this container, but if you got it working
yeah I think you should look at this container along with the rest of the script as it's just spaghetti to me
https://pastebin.com/XxjwyETH
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I think I'd have a container of HealthPlayers, and if it went into that first statement I'd just append them to a new list which I'd check every next iteration
This discord is so great, after trying to find a solution to my problem for a hour, I decided to ask for help here, but I found the solution by just explaining the problem 😂
ikr?
it's a very useful technique
it forces you to think about your problem enough to explain it
And it only took me like 30 minutes to code it 😄
This only happens in 2023. Confirmed it doesn't happen in 2022
submit a !bug report
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
I was trying to reproduce that but I must be thinking of another bug
I've got a question about default interface methods that I cannot seem to find an answer to online.
say I've got an interface that has a default method implementation on it and i've got a class that implements the interface, i want that method to do something extra rather than something different, so i want the default behavior and then some extra behavior that other objects implementing the interface don't need.
I can't seem to find a way to accomplish this without just explicitly implementing the interface method and copy/pasting the default implementation into the new implementation
is that really my only option if i don't want to turn the interface into an abstract class to inherit from?
good call. submitted.
for example since the code is quite long and this basically explains what i'm trying to do here:
public interface IFoo
{
public void Bar() => Debug.Log("Default Called");
}
public class Baz : MonoBehaviour, IFoo
{
void IFoo.Bar()
{
//i want the Default Called log to happen here
//then to proceed with the next bit
Debug.Log("Baz called");
}
}
I made a VisualEffect with visualeffect component, that works on a prefab, works if I drag it into the scene, but doesn't work if I instantiate the gameobject. Any advice?
odd, what's the error
I've had this issue before, but don't know how I did it 2 months ago
Have the default function call another default interface function that has a do-nothing default that can optionally be overridden?
the VFX just don't display on an object that is instantiated via prefab
yeah i just thought of that too. sounds a little jank but it'll get the job done 👍
I remember the solution being some really dumb checkbox in a menu in the VFX graph, I think? But i have no idea where it would be
vfx graph has some cold start or something, and I find stuff not rendering right away.
not really instance related, I think it's specific to the asset
I think I've read people will load each system at the start of the game then remove them from the scene
well, I can drag my prefab into the scene, but it won't show
hey so another thing with this
Currently I create a new command buffer every frame as i use flip-flopping textures that change their assignment each frame, is there a way to assign a temporary command buffer to a camera, so I dont end up adding an infinite amount of command buffers to the camera to render?
in my case, the VFX just don’t appear, even if I instantiate like 12 different prefabs at different times
strange. Only thing I can think of is you got some restriction on them and preventing them from playing
limited by spawned particles, paused, ect
post code?
in unity 2d for top down, what's the best way to create an effect with a paralax on a background image or tileset like this:
i have watched the same 20 minute tutorial for the entire month and i still can't comprehend
my brain just goes blank after 4 to 6 minutes
i could stare at a wall for 10 hours and it wouldn't be as painful
i just don't understand why i can't seem to get motivated, throughout my 3 years of game dev i only got as few as 5 months of actual work
i don't care, i was born to make games, even if my progress would take 10 times more time
dashing = true;
velocity = new Vector3(transform.forward.x * dashingPower, 0f, transform.forward.z * dashingPower);
yield return new WaitForSeconds(dashingTime);
velocity = Vector3.zero;
yield return new WaitForSeconds(dashingCooldown);
dashing = false;
how would i make this instead be an 8-way dash? with the direction based on the wasd input
instead of using transform.forward for the direction of movement, use your input. you'll likely need to use transform.TransformDirection to convert the input to world space direction first though
you can assign the command buffer once, then clear it after it has been executed. keep a reference to the command buffer. you can also use the command buffer pool. you can also avoid flip flopping render textures using the temporary render texture or RTHandles APIs, which sort of do the same thing
public interface IFoo
{
public void DefaultEffect() => Debug.Log("Default Called");
public void UserEffect();
public void Effect() {
DefaultEffect();
UserEffect();
}
}
can you call base.DefaultEffect() or IFoo.DefaultEffect()? I'm not sure. you can in java
you are better off using abstract base classes
I'm not sure the proper way to cancel this async function when its MonoBehavior has been destroyed. This throws an error which makes me believe I'm doing something wrong.
private async void SpawnEnergy()
{
while (true)
{
await Task.Delay(5000, destroyCancellationToken);
GameObject orbGameobject = Instantiate(orbPrefab, transform.position, Quaternion.identity);
Rigidbody orbRigidbody = orbGameobject.GetComponent<Rigidbody>();
orbRigidbody.AddForce(transform.forward, ForceMode.Impulse);
}
}
no, i went with this though #archived-code-general message
which is basically what you suggested with your first reply
default interface bodies can't call other interface methods?
i see
i assume internally c# makes an instance which implements the defaults
i understand why you cannot call into it because the interface implementor is not inheriting from that type
it’s a VFX graph
i can drag my prefab into the scene, and it works fine. but if my code instantiates it, the VFX do not display, even though aliveParticleCount is 20-400.
what is the error?
Tasks are complicated. what do you expect cancelling while Task.Delay is being awaited to do?
- The method "just" "stops" executing without any further baggage, like coroutines.
- Task.Delay throws an OperationCancelledException
- Task.Delay returns immediately and
destroyCancellationToken.IsCancellationRequestedreturns true. then, since the game object is destroyed,transform.positionthrows aNullReferenceException
I solved my issue about prefab instantiating VFX with a VisualEffect component that only doesn’t display when instantiated. I just had to fix my Orientation at the end.
My particle output had Orient to Camera, and I changed to a custom axis. idk why this made a difference, but it was indeed something dumb.
Hi, I'm starting to learn how to make meshes from code, I want to know how I can get the direction from one vertice to all vertices connected(all the edges). How do we get this information from a mesh and its vertices?
you'll need to use the triangles part of the mesh definition. Search through it to find all the triangles that reference the vertex in question.

do anyone know how to remove the interactable from xrsocket at runtime like by pressing the button
I'm sorry, I can't believe I left the error out. The error is "TaskCanceledException: A task was canceled". I expect the method to stop executing, like a coroutine. This happens when I stop running my program, so Destroy() is never called by me explicitly.
okay, so it's #2
you have to catch it and return
so
async void Blah() {
try {
your code
} catch (OperationCancelledException) {
}
}
no
it's not
it makes a lot of sense
think about the other situations i described
what do you expect to happen? gotta answer my question
I said I expect the method to stop executing, like a coroutine.
Without baggage, that is
I expect in most use cases throwing an error for a task is useful, not so much for stuff like this
What's the most efficient way to code a timer for a game? Running it from fixed/update would slow it down or would that be negligible?
like you want somthing to happen when the timer elapses? Update should be fine for that, as long as you don't have too many of them active at once.
Timer that counts how long you have survived, and displays it during the run.
If its just that it should be fine then right?
yes
I'd use Time.time for that tho. record it on start, then subtract to get current "survive time"
Nice thank you 😊
Keep in mind that Time.time is the time since the application started. So you would need to handle cases where the player can stop the game and come back later. That is very simple, just a consideration
But adding to a timer in Update or FixedUpdate is completely negligable too. Every piece of code you write occupies the main thread and technically "slows down" the game, but computers (even phones) are extremely fast. Adding a float to another float once a frame is, as said, completely negligable
Efficiency for something like that shouldn't really even need to be considered.
Profile things and fix them when they are an issue
quick question how can i stop my animation from endlessly looping
We're getting this error when building on macOS in Unity 2022.3.12
Has anyone seen this before? I believe it's only happening on one person's computer.
Building /Users/angusarnold/Desktop/MasterBuild.app/Contents/MacOS/Enter the Chronosphere failed with output:
System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.)
---> System.NullReferenceException: Object reference not set to an instance of an object.
at UnityEditor.OSXStandalone.CodeSigning.HashUtils.WriteHashString(Byte[] data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 41
at UnityEditor.OSXStandalone.CodeSigning.HashUtils.HashFile(NPath file, Byte[]& sha1Hash, Byte[]& sha256Hash) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 148
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignResourceFile(FileToSign file) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 243
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.<>c__DisplayClass9_1.<SignFilesWide>b__0() in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 193
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext,
[13:36]
ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignFilesWide(IReadOnlyCollection`1 files, Boolean warnAboutUnsignedChildBinariesInBundle) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 213
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.Sign(SignFlags signFlags, BundleSignTarget& signedBundle) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 59
at MacOSCodeSignBundleInPlace.Run(CSharpActionContext ctx, Data data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/MacStandalonePlayerBuildProgram/MacOSCodeSigning.cs:line 109
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) (at /Users/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:190)
There is a loop option. Do you want it to loop at all?
Oh, and probably better for #🏃┃animation
Looks like a code signing error to me. You could try not signing it in Unity if you can avoid it, and signing it in xcode in the next step (that's what I like to do normally). Just a guess though for my part
It's actually just a team member doing a debug build
Not a release
So ideally we don't need to sign at all, but I'm not sure how to disable it
This surprisingly crashes my game
Why on earth would a try catch block crash. 
hey so i have 2 questions
-
how do i make it so that my camera doesn't clip through walls while wall running?
-
how do i make the player not able to stick to walls when pressing A or D depending on which side the wall is on from them?
I have the wall running script so just ask if you need it please, i dont want to fill up the chat with a giant wall of code
Doesn't look like a coding question, try #💻┃unity-talk
Ok thank you
Hi i find myself trying to force my design patters im used to in game maker onto unity. For example in game maker inside game maker you could just go and say enemyTarget=instanceNearest(objEnemy,x,y) and then u csn say enemyTarget.BecomeDammaged(attackStrength);
So within one object you can entirely control another
But ive noticed in unity doing that is a whole ass exercise
So i was wondering maybe there is a better way to do this in unity
So i dont have to forcefully go thru all the scripts of the object then find said method then try and use it
why you cant do that in unity?.....
you havent really described what "this" is, i believe i suggested in a previous conversation to just use triggers to get nearby targets (and then you can sort it if u wish). This pushes your logic to another object, since you want this script on the same gameobject as your trigger collider. Whatever object does damage would also call GetComponent to look for a health script, which would likely happen on collision/trigger or raycast
i think before they were doing a static list of every single object that this magic instanceNearest method would use. You can do it, but they are now realizing why no one does it. it is a design nightmare
Well the instance nearest isnt really the important part the important part is you can just find the object id and then immediately begin changing its fields firing its functions,in Unity having to search through all the scripts and then all the functions to see if it even exists before using it feels wrong
Like im not coding correctly
you can reference specific component?
search through all the scripts and then all the functions to see if it even exists
It is one single GetComponent call if you are talking about getting a reference on a totally unknown gameobject
if we are talking about the same object, you just drag in the reference in the inspector
What's the actual problem?
What if you dont know the name of the script for example if the nearest object could be orc or skeleton one has a orcController script the other skeletonController script now you cant reference the script directly because you dont know which name it is
TryGetComponent and test the tag of the gameobject
Btw why you dont know the script of the gameobject
Also im not trying to say game maker is better im trying to say maybe game maker taught me bad coding practices and I am trying to learn better ones
this doesnt really matter, because if you dont know the name of the script you are searching for, then you likely dont need to do anything to that script. You can use inheritance in some cases to get any script which implements some methods but getting the controller of an object sounds wrong. You would likely only want to get the component related to their health
If there are 10 different enemy types and i now found one of them wouldnt that mean id have to switch case the name of the nearest ovject to then see what its appropriate script name is
Oh so scripts in unity are devided up like here is your health script here is your movement script?
read what bawsi say, you may need inheritance.
Ive been having just one script per object
Sorry i posted that reply just as he replied
Yes divide up your logic, it will solve your case here
Health is health, doesnt matter if it is a skeleton, orc, a wall you want to break. They all work the same, you hit it, it takes damage
I see , thank you i knew i was doing something wrong
Also my bad this should have been in the beginner channel
dont worry about how many scripts you have also, my player has 13 of my own right now
Unity seems to live much more in its IDE UI than game maker
I see
You can definitely use the inspector to setup very different enemies. you mentioned skeletonController and orcController before, but in unity you can pretty much just make one "AICharacter" script if you make your other code generic enough. The difference between a skeleton and orc is only the model and collider size. If you have a way to assign the attacks they can do in inspector, then there is no code different between them.
Also having health as its own component lets you setup other nice things, like if you want a skeleton that cannot be damaged (maybe it is a town NPC), then you simply dont add the health component. If you want a skeleton thats used in battle, it can have a health component. The AI code doesnt change
I have a prefab of road, it gets destroyed with a trigger collider, when a new prefab of road is instantiated, it does not get destroyed by that collider. Why is that? Need help
We dont know without seeing your scene setup and code
First of all, i'm not sure if u should be using the names of gameobjects as ids if that's what you're thinking.
I think interface would work better here. 
All characters might be hittable but not all hittables are characters.
#archived-code-general message
the last paragraph is why composition is better. its no longer limited to "All characters might be hittable", it is "this is hittable if i give it a health component". No other scripts needed
true. 🍿
Making my own game engine, gonna use composition for dictating parent/child hierarchies.
Hi i am trying to make a video player where when user hovers with their sprite then only it is visible so I am playiing a video on one sprite and and enabling one plain sprite on that video player sprite but when I am hovering with my sprite the video isn't visible
Hi everyone, I'm trying to rotate an object in a way that its transform.up would be aligned with the normal of the ground it is standing on, and at the same time indepedently rotate it around the y axis in order to reach a certain target.
When I do these rotations separately on my object, they work perfectly, but when I add them together, one of them always decides not to work properly.
In this implementation, the y rotation works, but the normal doesn't.
Any help would be greatly appreciated! 😃
Code snippet:
//Calculate the rotation based on the Y axis rotation
Quaternion yRotation = Quaternion.Euler(0, Time.deltaTime * currentAngularVelocity, 0);
//Calculate normal
Vector3 v1 = rightLegTargets[0].transform.position - leftLegTargets[^1].transform.position;
Vector3 v2 = rightLegTargets[^1].transform.position - leftLegTargets[0].transform.position;
Vector3 normal = Vector3.Cross(v1, v2).normalized;
//Calculate rotation to align transform.up with the normal vector
Quaternion normalRotation = Quaternion.LookRotation(transform.forward, normal);
//Combine the normal rotation and the Y-axis rotation
Quaternion combinedRotation = normalRotation * yRotation;
transform.rotation = combinedRotation;
I'm using an empty game object, with a collider. It has trigger checked on collider property, and the script attached to the road prefab has
Inside update
Private void OnColliderEnter(Collider, other)
{
If(other.gameObject.CompareTag("Road_Destroy_Tag"))
{
Destroy(gameObject);
Debug.Log("Road Destroyed");
}
Now the Tag "Road_Destroy_Tag" is applied on the collider, that detects the road prefab in the scene. The first time I run play mode, it destroys the road prefab, and the console shows it, but as soon as the new prefab of road is instantiated, as it passes through the destroying collider, it don't get destroyed, and the console don't show anything. This means it only works once
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I understand, but I just want to understand the concept, of why it's not destroying the newly instantiated road prefab, while it only destroys the one, which was already there in the first place
Private void OnColliderEnter(Collider, other)
{
If(other.gameObject.CompareTag("Road_Destroy_Tag"))
{
Destroy(gameObject);
Debug.Log("Road Destroyed");
}
This is the code that I'm using to destroy
What is on collider enter, there is no such message in monobehaviour, we have on collision or on trigger
Check the method really got fired or not, and your ide seems not configured
Not sure where to ask this, but how to disable alphabetical sort of serialized fields in rider?
It even says
<!-- Pattern to match classes used by Unity that contain serialised fields and event function methods. Based on the standard "Default Pattern", this will also order event functions before normal methods, and does not reorder serialised fields, as this order is reflected in the Unity editor's Inspector -->
in file layout setting.
But still sorts my [field: SerializeField]
I want to Intantiate a gameobject from the position of the player. The object acts as a projectile black hole. That causes the problem that when I try to summon the object, the player gets pulled in. This is intended behaviour, and such I don't want layer overrides. I just want to instantiate the gameObject a bit further up front (and possibly automatically adjusted depending on the radius value). What would be the best way to do that, since Vector3.forward just returns a fixed value and transform.forward a fixed axis?
Code:
// The attacking script
[SerializeField] Transform projectileSummon;
GameObject gluttony = Instantiate(Resources.Load("Prefabs/Gluttony") as GameObject, projectileSummon.position, projectileSummon.rotation);
gluttony.GetComponent<GluttonyBehaviour>().player = gameObject;
// The behavior script is in the pastebin
Getting a fixed axis may actually be helpful if I understand your scenario correctly - if you know the direction you want to put the object away from the player, and you know how far in that direction, say youd want to spawn it "12 meters infront of the player", then transform.forward returns "1 meter from the player", so transform.forward * 12f would return 12 meters from them, so origin + (transform.forward * 12f) would be 12 meters in the players forward direction, from some "origin", in this case, that origin sounds like your players position
thanks a lot. You are a lifesaver
I am unable to spawn GameObjects to clients. I get this error:
Unity.Netcode.NotListeningException: NetworkManager is not listening, start a server or host before spawning objects
how did you paste your code in the comment this way?
so I'm currently generating resources on my map by doing the following :
choosing a random point on the map
Then casting a ray from the top of the map to the bottom of the map and generating a resource wherever it lands
how would I calculate the rotation of the resource based on the slope of the surface that the raycast hit?
you add \``` before and after the code\```
how come it didnt work for my comment?
Ah thank you
that didnt work 😢
without the "\"
Hahah thank you
#archived-networking for networking related issues
but you're calling Spawn() on a NetworkObject before the server has started
Thank you. I'll ask further in there
hey guys, not sure where to post it but i can't compile for linux dedicated server build using ILCPP on my MacOS, it hangs on forever at Linking GameAssembly.so (x64). Is there a known issue or a workaround for that ?
are VFX components super expensive to instantiate or something?
I'm just noticing small lag spikes when I instantiate prefabs with a VisualEffect component on it
even if it is a super simple prefab with very little going on
im trying to make an equip and replace system in unity but im having the issue where weapons aren't getting replaced, rather just stack ontop of each other.
I already handle interactions in my controller script, here's the part related to guns
public void EquipGun(Transform gunTransform, Rigidbody gunRigidbody, BoxCollider gunCollider)
{
if (gunIsEquipped)
{
DropGun(gunTransform, gunRigidbody, gunCollider);
}
gunIsEquipped = true;
gunRigidbody.isKinematic = true;
gunCollider.isTrigger = true;
gunTransform.SetParent(gunContainer);
gunTransform.localPosition = Vector3.zero;
gunTransform.localEulerAngles = Vector3.zero;
}
public void DropGun(Transform gunTransform, Rigidbody gunRigidbody, BoxCollider gunCollider)
{
gunRigidbody.isKinematic = false;
gunCollider.isTrigger = false;
gunTransform.SetParent(null);
gunRigidbody.AddForce(playerCamera.transform.forward * dropForwardForce, ForceMode.Impulse);
gunRigidbody.AddForce(playerCamera.transform.up * dropUpwardForce, ForceMode.Impulse);
float random = UnityEngine.Random.Range(-1f, 1f);
gunRigidbody.AddTorque(new Vector3(random, random, random) * 10);
}```
Here's the part in the gun script:
```cs
[SerializeField] private FPSController player;
private Rigidbody gunRigidbody;
private BoxCollider gunCollider;
private void Awake()
{
gunRigidbody = GetComponent<Rigidbody>();
gunCollider = GetComponent<BoxCollider>();
}
public override void OnInteract()
{
player.EquipGun(gameObject.transform, gunRigidbody, gunCollider);
}```
I think i know what the problem is, in the first if statement, the script is referring to the gun already on the gorund therefore it doesnt drop anything, but im not sure how to store the already held gun's information for me to drop it. Or is there another way to do it?
yeah, what I do is my equipping script has a few layers to it
I have an attacher script and attachment script.
Attacher script has a reference to what is attached, and an interface on itself to let it know that what it attached is destroyed or something.
Attached thing gets a simple monobehaviour (AttachementScript) to communicate with the attacher.
In order:
Call Attacher.TryAddAttachedThing(). This checks if we already have something attached. If we want to allow it to replace, we need to call CurrentAttachmentScript.DisconnectMe(). Then we add the newly attached thing, giving it an AttachmentScript component.
ooooo
AttachmentScript.DisconnectMe() tells Attacher that the thing that is attached is disconnected, and to update its state automatically back to a blank state, where nothing is held
these aren't the names I use, but that's the general idea
yeah yeah i get it
I use a generic IEntityAttacher interface so different things can use this mechanism. Not just player holding a gun or whatever
not actually a generic, but to be used by many things
dayum, thanks for the idea <3
EntityAttachementHandler (the monobehaviour that goes on the gameobject), has a lot of separate little responsibilities for the attachement. Basically, it stores the state of the thing before it was grabbed, allows it to be changed, and sets it back if you drop it
for example, if you want to hold an item, and want player to not collide with it
EntityAttachmentHandler (when you tell it it is now being held by IEntityAttacher), can be set to automatically check for colliders, and disable collision between them. And it stores what it was before.
Then if you call the disconnect method, it brings the attached thing back to the original state.
This is the interface I use. Might be helpful to give you an idea:
public interface IEntityAttacher {
/// <summary> Tell the attacher (parent) that its child has been disconnected.
/// The argument tells you which handler specifically is requesting disconnection (in case of inter-transfer jank).</summary>
public void DisconnectChild(EntityAttachmentHandler childRequesting);
/// <summary> Return a reference to the child attachment handler that is currently attached. Return null if there is no child. </summary>
public EntityAttachmentHandler childAttachmentHandler { get; }
public GameObject gameObject { get; } // gameobject the script is on.
/// <summary> Rigidbody for the attacher (parent). This may or may not be on the same gameObject! </summary>
public Rigidbody2D AttacherRigidBody { get; }
}```
On small detail that should be obvious: Part of the whole point of this is to make sure the moment the parent dies etc that the child is immediately notified (to no longer have the properties of being held). And if child dies/destroyed/etc, it also immediately notifies parent that now nothing is attached (so it can hold something again).
The existence of the EntityAttachmentHandler script on a gameobject also indicates if something is already attached/held to something else.
eg you don’t want one player grabbing a gun out of an NPC’s hand
Im tryin to make some UI for my game
But I find that if I change the layout of my editor, the UI elements change a lot
SO I changed it to scale with screen szie
huh ? where is the code question?
But then when I change it the UI became ridiculuously small
Oh Right maybe its better to ask in UI
Not really a code issue
Where can I ask for help?
Ah, I missed the image. Which pipeline is it?
#archived-urp
#archived-hdrp
#💻┃unity-talk if neither of the others I guess
Thank you!
Excuse me guys, i have a question. I'm making a script where a certain part of the code is executed only when it's not in play mode (in Editor). So I'm using !EditorApplication.isPlaying as a check. If i add this to my script that uses MonoBehaviour, first question, will it able to check !EditorApplication.isPlaying if i turn off the play mode, second question, should i use #if UNITY_EDITOR #endif so it wont cause error when build?
yes for both
wokey
okay i have an update, it seems its failed to run the method when editor is not in play mode
is there a reason to this?
private void Update()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
Reset();
}
#endif
}
Do you have the [ExecuteAlways] attribute on your class?
By default, methods like Update will not run in edit-mode
no, i already think of adding it, but the thing is, since its always run either in play or edit mode, wont it cost a heavy toll on the memories?
not to mention i have a certain game logic in this script, is there an another way?
it will cost exactly as much as you make it cost
Depends on what you are trying to do
Explain what you're trying to do.
not "run code when not in play mode"
what are you trying to accomplish?
As is, we can only interpret that you're wanting the code to always run - including in the editor (non play mode)
i want to reset a certain value in my scripts variable when it stops play mode, because i have a static variable that stores some values, its more like a way to help my game designer not to make some human error mistakes. But overall in game, this value wont need to be reset, only when making levels or design in the editor. It stores some state that will persist on scene changes, thats why i made it as a static (i didnt use singleton pattern because of one and another conditions)
If you want to reset something when you exit play mode, just subscribe to Application.quitting
you can conditionally do so with #if UNITY_EDITOR so that it doesn't run in the built game, if that matters
i already made manual button to reset in editor, but someday my game designer would forget
i think i might try this
I don't think there's an equivalent to https://docs.unity3d.com/2020.1/Documentation/ScriptReference/InitializeOnEnterPlayModeAttribute.html for exiting play mode, unfortunately
there is a callback function when playmode change
Is there something better I can do than indexof(Texture) to find a matching texture in an array? I assume the comparison for texture obejcts is quite expensive but is there any other like hash value that doesnt change for the texture I can use instead?
I think it's as expensive as any type that inherits from object.
Texture comparison is not any more expensive than any other object comparison. They're just references.
That being said maybe you should use a dictionary
yeah looking into a dictionary now thanks!!
as this is pretty rough
should I use the instanceid of a texture for comparison/keys?
using unity authentication, how do i check if a saved session token is an anon account or linked to a username/password account?
you would sign them in Anonymous first
To verify if a session token is currently cached for the current profile, use AuthenticationService.Instance.SessionTokenExists
If the session token exists, then the SignInAnonymouslyAsync() method recovers the existing credentials of a player, regardless of whether they signed in anonymously or through a platform account. A code example would look like this:
https://docs.unity.com/ugs/en-us/manual/authentication/manual/cached-players
oh so if they signed in as a normal account, SignInAnonymouslyAsync() will sign them back into that emai;/password account?
it should sign in the same user yes
Dope
what about if i want to use what im logged in as rn? like if im using anon or if i have actual username/password
Are there any memory worries or anything if I use dictionary<int, texture2d> vs list<texture2d>?
what do you mean
like cuz i wanna display a screen if they're logged in as anon
and another screen if they're logged in as another provider
like username/password
are you talking about a cached user ?
are anon users not cached?
they are
They have different use cases. The Dictionary is unsorted but faster when getting an element from its key (the int value here).
yeee I know thats what im using it for instead of list.indexof
not compiled
They can't be datamined?
they don't exist
IndexOf retrieves the key from a value basically. The Dictionary is better at doing the inverse
they aren't even part of the build so no
wait so its not much faster to do ListB[ListA.indexof(texture)] vs Dictionary(Texture.InstanceID)?
In that specific case it is faster
But if you use the Dictionary value to get the key, you're doing it wrong. The Dictionary is backwards
oh no sorry Im using the dictionary key as an index into related arrays
I go from key to value not from value to key
im just worried that theres some memory "gotchya" about dictionarys over lists I need to consider
Don't use them backwards, and, they cannot be duplicate keys in one Dictionary
The second point is not an issue since you're using IDs
yeee thats specifically why I wanted dictionarys really, the whole list and indexof was to check for duplicates
wouldn't a hashset work fine too if you're just doing a ref lookup?
the thing with the list was linear searching, but if you're not using a kvp then the hashset should be fine.
either way they're usually similar
then how do i differentiate between the type of acc?
Can anyone recommend a nice events library that allows me to easily send data between objects?
I don't want to mess around in the inspector too much either..
why do you need a library for that? just get a reference and either use events or just directly pass the data
I want to eventually plug in new systems easily
And I want to trigger multiple actions at once
e.g. on x event, i want to trigger an action on object a and b
Wouldn't I have to pass this event variable around to all objects though?
you just need to get a reference to the object that has the event
Would creating an event singleton work?
if you really insist on using some library, there are frameworks like extenject which allow you to set up dependency injection containers
the caveat to using things like that is that you don't need it unless you know you need it and know why you need it
https://github.com/kyubuns/Kuchen I think I might be looking for something like this, but there's something about this that seems wrong
a vague "I want to eventually plug in new systems easily" isn't really enough to actually need something like that
I plan on making an input manager that holds the PlayerInput components and emits those events to the player and things like UI
interacts etc
I also want to not be dependent on the inspector
why
the inspector gives you an incredibly easy to manage simple dependency injection
i work in many scenes and cant be bothered to drag references here and there (among other things)
Iirc they have that stored inside PlayerInfo
alr
does GetUnityId refer to username/acc system
i can get a bunch of different ids
but i can't see one related to username/password
if it has a Username, than its logged in with Username/Password
But can't anon accounts also have usernames?
Wat
I'm pretty sure my anon acc has a username
I added it tho, it's not by default tho
you mean you manually assigned it via the PlayerInfo ?
I did await AuthenticationService.Instance.UpdatePlayerNameAsync("Player");
When I log in as anon for the first time
PlayerName and username are different things @native folio
and yes Unity auto Generates a "unique" PlayerName regardless
username is exclusive to username/pass login
you can see here when you go to Anonym to username/pass
you MUST provide username for that reason
https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-username-password
Yeah this isn't great since it's string based. This is similar but type based
https://github.com/PeturDarri/GenericEventBus
This seems much better than the one I sent. Will defo check out, thank you!!
It does?
I recommend using the wip/replace-conditional-weak-table branch instead of master. There are some bugs on the master branch that are fixed with this branch.
The player name is null when i create an anon account
Pretty sure it does.
How are you grabbing the name ?
AuthenticationService.Instance.PlayerName
oh thats why
var name = await AuthenticationService.Instance.GetPlayerNameAsync();
Debug.Log(name);```
do this , should show you the name
I'm doing a whole video series on UGS/Player Accounts, I'm certain unity generates one each time 
yeah it just throws random words + # numbers
neat
😼
I made a post for improving the Dashboard, hopefully Unity listens
https://forum.unity.com/threads/enhancement-in-player-management-dashboard-usernames-player-managerment.1521895/#post-9502780
🙏
we need username searching asap 😮
Is there an event or something I can listen to detect when/if the player name changes?
good question, not sure if there is a built in way or you'd have to manually keep track
you can
got it
btw is there anwyay to configure the default username for anon accounts?
like max length, etc?
in what way ?
like dis
Oh actually Username i think can't be changed, and no you wouldn't be able to modify its min/max length
you would think Unity would think about this shit when they rollout features
sadly you can't do any of that shit with username/password
if you must have better control, I would just opt in for the Unity Player Accounts
which allows user to sign up with email and password + password resets n all that jazz
the upside is that Unity player Accounts also lets you sign up with Google/Apple too already integrated
so users only deal with those Identity provider
same reason why Username/password doesn't have Two-Step auth , its a very basic feature with bare minimum, and resetting a password isn't trivial thing (if you ever had to do this manually you know the pain)
the Unity Player Accounts signs in safely through the browser
looks something like this
i have this video if you want to see how it works
https://youtu.be/XVqYIFcjhLE?si=6xLIMWoZSI8PSIBV
0:33 - Installing Authentication Package
0:58 - Connect Project
1:14 - Adding Player Accounts to Identity
1:27 - Client ID from Dashboard
1:40 - LoginController script
3:26 - UILogin script
6:40 -Testing
6:55 - Google Login
7:05 - Logged In
7:21 - Exporting to android
8:22 - Testing Android
8:34 - Matching Ids
Quick disclaimer:
I usually don't...
i saw a video on storing passwords. the safest way is to not store passwords, and use another service with better safety, like Microsoft or Google SSO
what would be nice is if Unity had a feature to auto connect to whatever platform account you use. idk if that is a thing
like connect to steam profile, or PSN, or Nintendo, etc
thats pretty much what their doing
oh cool. is it out?
they already have these so far
I'm guesing nintendo / psn ones are harder because of NDA
nice. I might regret asking this, but is is easy/fast to implement?
easy as Pi
nice
if PSN /nintendo has sign in api you can prob use the OpenID/CustomID option
They may just not be listed there because the details are under NDA
I mean it does say its already there. its probably hidden if you dont have approval /nda agreement
Unity Authentication currently supports the following identity providers: Apple, Apple Game Center, Google Play, Facebook, Steam, Oculus (Meta Quest), Nintendo Switch™, PlayStation 4 and 5, Xbox, OpenID Connect, and Unity Player Accounts.
ah yes..was just saying that
nice
Hello. Can someone tell me pls if I can use the IgnoreCollision method to make the ray ignore objects with a specific tag. An example is below.
public class RaycastLearn : MonoBehaviour
{
public string[] tagsToIgnore = { "Base", "Wall" };
public GameObject[] objectsToIgnore;
void Update()
{
Vector3 rayOrigin = transform.position;
Vector3 rayDirection = transform.forward;
RaycastHit hit;
foreach (string tagToIgnore in tagsToIgnore)
{
objectsToIgnore = GameObject.FindGameObjectsWithTag(tagToIgnore);
}
foreach (GameObject objToIgnore in objectsToIgnore)
{
Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), objToIgnore.GetComponent<Collider>());
}
if (Physics.Raycast(rayOrigin, rayDirection, out hit, Mathf.Infinity))
{
Debug.Log("Hit object: " + hit.collider.gameObject.name);
}
Debug.DrawRay(rayOrigin, rayDirection * 10f, Color.green);
}
}
why not put them in a seperate layer ?
and ignore that layer
mb, but can i do it like that?
like what ?
the way I said it ? sure thats why I said it lol
Fuck, you're right, for some reason I didn't think to make a separate layer for them xD
No, how about using my example? or IgnoreCollision doesn 't work with Raycast?
ignoreCollision doesn't care about raycasts
it just ignores 2 colliders from each other
bad(
All the best to you, thank you for your help.
interesting
but like i dont want it to be branded with unity shit everywhere
hmm yeah it's a pickle
do note that you can also use unity but make your own OpenID style auth
its more complex though so I just don't mind the unity auth
ic
move.isOn = g.All(x => x.GetComponent<Moving>().isEnabled);```
For context:
- `move` is a Toggle
- `g` is a GameObject array
- `.All` is a LINQ function
- `isEnabled` is a boolean
Would this work? I'm not too experienced with using this LINQ function
Would it work? That depends on what your intentions are
It will certainly compile and run
my intentions are to check if every single array's moving component is enabled
Then yes
not sure how to use that inside of a .All function though
something like this maybe? i'm not sure
g.All(x => x.GetComponent<Moving>().wait == x.GetComponent<Moving>().wait)```
although that doesn't really make sense\
this should get vertices and tris from the gpu right?
check if every single gameobject's moving component's wait paremeter is the same
They can directly be used in the All function
well no, because x is a gameobject
So? We're talking about comparison operators
how would I use them in a function like this that's what I'm confused about
Same way you're doing it now
float first = g[0]. GetComponent<Whatever>().wait;
bool allSame =g.All(x => x.GetComponent<Whatever>().wait == first);```
I'm typing on the phone
ohh sorry i completely forgot doing it that way and was trying to compare everything with everything if that makes sense
i've been coding for too long
anyways thanks
Since handles are apparently only usable in editors is there a way to use them in normal scripts for builds?
I just want to be absolutely certain mainly because I don't want to have to code my own for actual use in builds
can draw gizmos I think
gizmos do not draw in builds
Handles are a part of the UnityEditor namespace, anything a part of that namespace cannot be included ina build since Unity doesnt also package the entire editor with your games, so AFAIK there is no native way of including them though I believe raycasts can be included with Debug.DrawRay or Debug.DrawLine, there may also be assets or github projects that have in-build approaches, one somewhat "simple" approach that comes to mind is to use primitive shapes as wireframes, which you could do in a free program like Blender, this does mean your including a wireframe mesh in your builds and resizing that mesh and potentially the material to give it a color for a build, so youd likely want to use a unlit material so its not affected by shadows and lights in your scene, maybe a depth shader so it renders infront of other objects if that matters for you - though I could be wrong and there may be a way, just not one ive heard of
I think I'd be able to draw a wireframe mesh with Gizmos but I'll look at the GL library. Thanks for the answers kind of disappointed its an editor only thing since it doesn't really seem that useful lol
GL library is pretty easy once you get the hang of it
Quite frankly this looks terrifying
(It has the word matrix and I don't like that)
Graphics mathhhs
Real
Good thing Unity has neat methods that do most of the work
https://gdl.space/yomucocosa.cs my character is not moving vertically
I don't understand why the vertical input is being read
wdym vertically ? this moves XZ
well yea it's not moving on the Z
can you show your setup
the inspector for this obj