#archived-code-general
1 messages ยท Page 66 of 1
I do want to select the objects that are really far away so that would have to be set quite high
alright thanks I guess its the easiest too
I don't know how accurate it will be when things become that far though.
well I'll try if it doesent work I'll keep looking
a concern would be that players with lower framerates will have a hard time clicking things at distance without some kind of aim assist
I guess a spherecast could help then
it could get stuck on some obstacle along the way
but worry about that stuff later, for now just get it working
dont fix what isnt broken
.
perhaps youre calling this coroutine every frame
I fixed it in the end by adding a bool
though this is a pretty inefficient way of implementing this
and something else
it's better to just use deltaTime instead of a coroutine
delta?
if you increase a value by x * Time.deltaTime every Update, it will increase at a constant speed of x
what are you trying to make then
Well it's quite hard to explain
it worked this is the final code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
IEnumerator CalculateTrajectory(Bullet bullet)
{
while (true)
{
bullet.flightTime += 0.1f;
//print("Fire1");
bullet.lastPosition.x = 0.0f;
bullet.lastPosition.y = bullet.startPosition.y + bullet.height;
bullet.lastPosition.z = bullet.startPosition.z + bullet.distance;
CalculateZDev(bullet);
CalculateYDev(bullet);
bullet.newPosition.x = 0.0f;
bullet.newPosition.y = bullet.startPosition.y + bullet.height;
bullet.newPosition.z = bullet.startPosition.z + bullet.distance;
//print("FlightTime:" + bullet.flightTime);
print(bullet.lastPosition);
if (Physics.Raycast(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Vector3.Distance(bullet.lastPosition,bullet.newPosition)))
{
print("Hit.");
}
Debug.DrawRay(transform.TransformPoint(bullet.lastPosition), transform.TransformDirection(bullet.newPosition - bullet.lastPosition), Color.green, 5.0f);
yield return new WaitForSeconds(0.1f);
}
}
I've tried sending this in beginner but nobody else has had much luck so perhaps someone in here might find something.
I'm trying to make a raycast based ballistic system. Problem is the rays are acting up and I'm not entirely sure why. Any ideas?
This is what it should, and did, look like. Problem is that the rays would not shoot out in transform.forward.
what do the calculate methods do? And you perform the raycast as though the bullet position were already in world space, but then you transform it anyways so either the raycast is wrong or the debug line is wrong
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.
Im trying to create a simple dialogue system
but im having trouble switching between each dialogue
whenever the player presses e again
can anyone help
I always get dialogue3 the first
and nothing else
They calculate the bullet height and distance at a specific time step.
It's probably the debug line that is wrong, however I'm not sure how to make sure the bullet leaves at transform.forward as opposed to remaining in the same direction regardless of the direction the character is facing.
Where's your press e code
if(Input.GetKey("e") &&distance>Vector3.Distance(player.position, npc.position)){
if(Physics.Raycast(r,out hit,distance)){
add(b);
StartCoroutine(Dialogue1());
}}
Use GetKeyDown(KeyCode.E) instead of "E" won't fix your problem but it's a better way
ok
Hard to say without seeing how you're actually calculating the bullet position, but they're probably both wrong since it looks like the curve has some x offset to it, which your raycast does not account for
In calculateydev, flight time should be bullet.flighttime - it's been fixed
You repeat and if statement twice here
Else if statement
@sudden crest
else if(b == 1){
count = 1;
b = 2;
return;
}
else if(b == 1){
count = 2;
return;
}```
You might have a mistake here
whats a good way to step through an algorithm and also draw the results out via gizmos ? if using VS step through the gizmos wont draw so its not helpful
its useless reading the variable data as its just too many numbers to track to know wtf is going on
the line is continuous when I run this. Raycasting does not match your trajectory and line 82 of the script you posted does integer division that zeroes out your second term
I'm trying to fix the debug ray before I attempt to implement it into the actual raycast. While the actual ray cast is continuous, you cannot turn with it.
What do you mean by second term?
(1/2 * gravity * Mathf.Pow(bullet.flightTime, 2.0f)) evaluates to 0
i see
let me try fixing it
why? flighttime increases by 0.01 every 0.01 seconds.
1/2 does integer division = 0
0 * gravity * Mathf(...) = 0
make one a float or use 0.5f
ooh, sorry. misunderstood what you said, ty
Done that. When you said that the line is continuous did you remove transform.TransformPoint, etc. ?
no, copied as-is, moved your trajectory into start instead of on button press with no other changes
do you have any scaling on your object?
that's probably what's happening here
on my gun object
which part?
TransformDirection takes scale into account. Switch to TransformVector
Will do
That's done it, you're a legend.
Although when I look around while a bullet is moving, the bullet also seems to move around
whoops, got them reversed actually. This means your trajectory is affected by scale though, that's probably not what you want. Why not just use world position the whole way through?
yes, because you're transforming the path by the shooter's position, rotation, and scale
I cant look around if I use world position, the bullet will only fire in 1 direction
? it's just a coordinate system. Presumably your bullet should no longer be affected by the shooter's position once fired, so convert local -> world on shoot, then deal in world position thereafter. It'll make the raycasting correct too
You've lost me. I though that if it's in world space, the z axis would not be relative to the player (i.e not being transform.forward) but only being in the z direction at any given time meaning if the player is facing in the x direction the bullet would go sideways?
transform.forward is "in world space"
As long as you have a way to pass that to the projectile at the right time, and you make the bullet follow that direction, it'll work
// Gun
var clone = Instantiate(prefab);
clone.transform.forward = transform.forward;
// Bullet
transform.position += transform.forward * step;
^ Will work whatever your current rotation is
I couldnt figure out a way to implement it into a raycast though, given that I already have the direction: bullet.newPosition - bullet.lastPosition
in
Debug.DrawRay(transform.TransformPoint(bullet.lastPosition), transform.TransformVector(bullet.newPosition - bullet.lastPosition), Color.green, 5.0f);
As simple as calculating the direction from the last pos to the current one, with the right distance
Vector3 dir = curPos - lastPos;
float distance = dir.magnitude;
dir.Normalize();
Physics.Raycast(lastPos, dir, out _, distance);
whats curPos?
No point or direction transformations, everything is in world space already
Projectile's current position
In world space
ah, for some reason i read it as cursor position
Ah yeah, I guess it can be interpreted like that too
It doesn't really work as it should:
If you can see those tiny green dots
Looks like the positions you feed in the direction/distance calculation aren't right
wait for debug, do I have to times the direction and distance together?
Depends, are you using DrawRay?
yep
Yeah you need to multiply the second arg with the distance
It only shoots in one direction
So that depends on how you move that projectile in code
How should I be moving it?
Current Code for context:
IEnumerator CalculateTrajectory(Bullet bullet)
{
while (true)
{
bullet.flightTime += 0.1f;
//print("Fire1");
bullet.lastPosition.x = 0.0f;
bullet.lastPosition.y = bullet.newPosition.y;
bullet.lastPosition.z = bullet.newPosition.z;
CalculateZDev(bullet);
CalculateYDev(bullet);
bullet.newPosition.x = 0.0f;
bullet.newPosition.y = bullet.startPosition.y + bullet.height;
bullet.newPosition.z = bullet.startPosition.z + bullet.distance;
//print("FlightTime:" + bullet.flightTime);
print(bullet.lastPosition);
Vector3 direction = bullet.newPosition - bullet.lastPosition;
float distance = direction.magnitude;
direction.Normalize();
if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
{
print("Hit.");
}
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
yield return new WaitForSeconds(0.1f);
}
Not sure, nothing actually moves an object here. Is the bullet an object in the scene, or purely a class instance in code?
purely a class instance
Okay I see, interesting way of doing it!
So, upon creating the bullet instance, you should pass whatever "forward" it needs to go into a field or property
Could be as easy as bullet.forwardDirection = transform.forward
Then you set up the movement around that variable
so once I have bullet.forwardDirection, do I add bullet.height and bullet.distance (the height and distance of the new position) onto that?
I think so, if I understand it correctly the "distance" and "height" simulate bullet drop?
yup
Sorry for somewhat leaching off of you rn, I'm half asleep but want to finish this so that I can sleep peacefully instead of brainstorming how to fix this. I've been trying to fix this for a few days now.
Okay I see now how it's working. So yes, you'd need to add the deviation values, move towards the next position using the "forward direction" variable, and recalculate that "forward direction" value so it accounts for the previous deviation you just applied
aight ty
Could I just add my direction variable to bullet.forwardDirection?
or am i being dumb
prior to normalizing it
No these aren't related until after you shoot the raycast
If you do that, you'll lose the deviation, and your bullet will fly straight
Raycasting downwards
It'll do something like that:
Dotted: bullet travel path
Solid: raycast direction
Ook
and where do i put my bullet.forwardDirection variable once i've added distance and height to it's z and y?
Summed up, the whole process goes like that:
Initialize the forward direction when the instance is created.
Compute deviation, and add it to the forward direction. Move your bullet to that new position.
Compute the direction/distance for the raycast and fire it.
Update the forward direction to be the raycast direction we just created, so devialtion is accounted for.
Repeat the past 3 instructions until the bullet needs to be destroyed
The forward direction doesn't get updated until the very end of a "step" (an iteration)
It'll look like this in the end:
(I've offset the arrows so you see them, in reality they overlap)
that's the deviation from currentposition correct? or from origin?
From the current position, if you re-calculate and apply a deviation for each iteration
You do
Yep; but current is the one after you apply the deviation
I'm trying to make a randomly generated map with rooms that connect with eachother here is my script: // Add an opening to the connector room where the new room is attached
GameObject connectorRoom = GameObject.FindGameObjectWithTag("Connector");
Vector3 openingPosition = connectorRoom.transform.InverseTransformPoint(newPosition);
if (opening == Vector3.forward)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Front, openingPosition);
}
else if (opening == Vector3.right)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Right, openingPosition);
}
else if (opening == Vector3.back)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Back, openingPosition);
} I'm getting the error NullReferenceException: Object reference not set to an instance of an object
Generator.Start () (at Assets/scripts/Generator.cs:113) and I'm not sure what to do. I've already tagged the prefab of the connector as a "Connector".
transforms are not static the origin is being updated
So you can't know the value of current before you apply the deviation, and apply that to your position
In my schema above, there would be 4 deviation recalculations (don't forget the one at the starting point)
So, 4 positions moves, 4 previous-to-current-direction calculations, 4 raycasts, and 3 "forward direction" recalculations (since the first one is pre-calculated when you spawn the bullet)
What is line 113
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Right, openingPosition);
You'll have to debug a bit as there are two possibilities here. Either connectorRoom is not assigned (is null), or it didn't have a Room script attached at the time this code ran
I reran the game and it gave me the same error message so I am assuming it would have to be the first one but is connectorRoom not assigned throuh the connector tag?
Through a tag?
Ah yeah right
If it was null it would have thrown the error on the line where you do the InverseTransformPoint stuff
So, it doesn't have a Room component attached
FindObjectWithTag might be picking up another object you tagged "Connector" by accident?
Where'd I go wrong? It doesn't work.
IEnumerator CalculateTrajectory(Bullet bullet)
{
while (true)
{
bullet.flightTime += 0.1f;
bullet.lastPosition = bullet.newPosition;
CalculateYDev(bullet);
CalculateZDev(bullet);
bullet.forwardDirection.y = bullet.height;
bullet.forwardDirection.z = bullet.distance;
bullet.newPosition = bullet.forwardDirection;
Vector3 direction = bullet.newPosition - bullet.lastPosition;
float distance = direction.magnitude;
direction.Normalize();
if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
{
print("Hit.");
}
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
yield return new WaitForSeconds(0.1f);
}
}
Again, you don't touch the forward direction until the very end
And especially don't put the deviation values in it!
Isn't that step 2?
You add them to the current position, to get the new position
bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
I've been looking around and I cant seem to find a nice way to handle collision between different teams and their projectiles. Would I really just have to make a collision layer for each teams projectile and units?
I'm looking for this kind of interaction
Every team should collide with eachother and not themselves
Every teams projectiles should collide with eachother but not their team or their teams projectiles
Like this?:
IEnumerator CalculateTrajectory(Bullet bullet)
{
while (true)
{
bullet.flightTime += 0.1f;
bullet.lastPosition = bullet.newPosition;
CalculateYDev(bullet);
CalculateZDev(bullet);
bullet.newPosition.y = bullet.forwardDirection.y + bullet.height;
bullet.newPosition.z = bullet.forwardDirection.z + bullet.distance;
Vector3 direction = bullet.newPosition - bullet.lastPosition;
float distance = direction.magnitude;
direction.Normalize();
if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
{
print("Hit.");
}
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
bullet.forwardDirection = direction;
yield return new WaitForSeconds(0.1f);
}
}
Almost, += for the two newPosition sets
Otherwise they'll stay near the world origin as it's not added to the current position anymore
still remains in same direction:
Maybe it's an optical illusion with the grid, but I see a drop here
Oh no, it does drop. The gun is facing the opposite direction.
Do any solo devs have insight on what ticketing systems they use to ticket work on their projects, if any do? I find that without using some kind of system (ie, Trello, Monday, a spreadsheet, something) I get way too disorganized too fast.
I'm shooting in the air here
I was able to delete the tag after removing it from the one connector prefab I knew the tag was applied to meaning I didnโt apply the tag to any other game objects accidentally.
Can you debug-log out the bullet.forwardDirection before the while loop in the coroutine?
IEnumerator CalculateTrajectory(Bullet bullet)
{
print(bullet.forwardDirection);
while (true)
{
bullet.flightTime += 0.1f;
bullet.lastPosition = bullet.newPosition;
CalculateYDev(bullet);
CalculateZDev(bullet);
bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
Vector3 direction = bullet.newPosition - bullet.lastPosition;
float distance = direction.magnitude;
direction.Normalize();
if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
{
print("Hit.");
}
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
bullet.forwardDirection = direction;
yield return new WaitForSeconds(0.1f);
}
}
No output
Then that code isn't running, or you disabled info messages in the console
wait i may have collapsed everything
Any one know why i get "supplied vertex array has less vertices than triangle array" and for uvs i get "supplied array needs to be same size as mesh.vertices array"
For this code:
int vertexIndex = 0;
for (int i = 0; i < _data.Triangles.Count; i++)
{
Triangle triangle = _data.Triangles[i];
_verts.Add(triangle.A.xyz());
_verts.Add(triangle.B.xyz());
_verts.Add(triangle.C.xyz());
_uvs.Add(triangle.A);
_uvs.Add(triangle.B);
_uvs.Add(triangle.C);
_tris.Add(vertexIndex);
_tris.Add(vertexIndex+1);
_tris.Add(vertexIndex+2);
vertexIndex += 3;
}
This is the output: (0.27, -0.31, 0.91)
I accidentally collapsed the logs
Okay that's definitely not pointing where the bullet is going
The vector looks like a correct direction vector, so the issue does not come from there
Try stripping out the deviation calculations for now, and try again but this time by adding a constant value each step, on one line, like so
bullet.currentPosition += bullet.forwardDirection * 100;
That should be propelling it at 10 units per second towards whatever forward direction
And strip the code after that line too
Vector3 direction = bullet.newPosition - bullet.lastPosition;
this?
print(bullet.forwardDirection);
while (true)
{
bullet.flightTime += 0.1f;
bullet.lastPosition = bullet.newPosition;
CalculateYDev(bullet);
CalculateZDev(bullet);
// bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
// bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
bullets.newPosition += bullet.forwardDirection * 100;
// Vector3 direction = bullet.newPosition - bullet.lastPosition;
// float distance = direction.magnitude;
// direction.Normalize();
// if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
// {
// print("Hit.");
// }
// Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
// bullet.forwardDirection = direction;
yield return new WaitForSeconds(0.1f);
}
Like so?
Yep looks good
Ah forgot there's no object in the scene sorry
Draw a ray from last position to new position in that loop
Debug.DrawRay(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Color.green, 15.0f);
@simple egret
Does it draw towards where you're shooting at?
yup
Testing stuff on my side, hang on
aight
Is it possible to access MonoBehaviour scripts through editor window scripts?
If so how
Okay I came up with something that works, but the catch is that the drop is measured with a Quaternion ๐
But it seems like it's working correctly
hi is it possible to initialize an empty gameobject without a prefab ?
new GameObject()
How does that even work?
The drop is a rotational value instead of two values. Like "-5 degrees per step"
Thanks ๐
Code sample. No Unity so I had to hard-code the quaternion XYZW values taken from an online converter (it wouldn't let me use Quaternion.Euler)
But you can see the direction gradually falling over each iteration, and the Y position falls exponentially
lmao if I put on more iterations the bullet goes in circles as expected
3am, it's bed time
Feel free to ping me if you solve it in the meantime
Is it possible to access MonoBehaviour scripts through editor window scripts
hey,
what is the right way to set Rect transform ?
is it LocalPosition or something else ?
i meant via code
I wanna set left, top,Pos Z , right , Bottom to zero and also change the anchor present
rectTransform.anchorMax, rectTransform.rect.left. There is also rectTransform.anchoredPosition for moving it around, but it's a real pain to do this via code, I would recommend using Prefabs and Unitys Layout System.
If you make changes to the rect you also have to reassign it:
RectTransform t = GetComponent<RectTransform>();
Rect rect = t.rect;
rect.left = 4;
t.rect = rect;
@solemn raven Consider setting .anchorMin, .anchorMax, anchoredPosition and .sizeDelta. The transform stuff in the inspector is derivative of how the underlying data is actually stored.
Thanks ! โค๏ธ
Thanks for the tip โค๏ธ
Ok so I'm trying to make it so the player slides down slopes that are too steep
{
if (Physics.SphereCast(player.transform.position,Controller.radius,Vector3.down,out slopeHit,player.groundMask))
{
hitNormal = slopeHit.normal;
return Vector3.Angle(Vector3.up, hitNormal) > Controller.slopeLimit;
}
else
{
return false;
}
}```
but for some reason the sphere cast isnt working
for some reason if the direction is something other than down it works, but it doesnt work right
Vector3.Angle() looks suspicious to me. Maybe print that line while playing to see if it gives the result that you expect? Otherwise, is the sphere casting far enough for your case?
I would generally use a dot product of your normal and the world up direction rather than measure in degrees (+1 for if normal is same as up, -1 if they're totally opposite). @marble halo
I tried printing and I always get an angle of 0 for some reason
The normal of a floor is "up", if your controller is being pulling into it from above.
So the good news is that it seems your code is working... ๐
where would i use dot
You don't need to do that, I think your approach is fine. Just consider this: Vector3.up - Vector3.up == ?
Remember, your floor normal is looking at the sky, assuming gravity is pulling your character down. @marble halo
but the sphere cast still gets nothing
why wont the damn thing work?
also slopes dont point up
Oh, if you're getting 0 on slopes too, then I misunderstood what you were reporting.
Are you possibly interacting with yourself? Edit: probably not if you're checking for ground.
player.groundMask this should only check the ground layer though?
its not set to player
If your ground layer and layermask contain the right values, then you would think so, yes.
Your Angle math is backwards anyway; what I mentioned earlier is definitely still going to be an issue.
hello! I'm experimenting with changing a UI panel's rectTransform through code but don't know exactly how. Do any of you have any experience with this?
#archived-code-general message Was just recently discussed, actually.
perfect. Thank you!
@marble halo You're definitely colliding with something if your code is getting far enough to report 0. I'm thinking that you might be measuring an interaction with your own player because of how the value never changes. Use of Angle() should give you 0 when hitNormal is also exactly Vector3.up. Does your player stay upright at all times? That would give a 0 result if it's being matched by your ground mask.
player does stay upright at all times
not even sure how you can rotate the character controller
@marble halo Well, since you're for sure colliding with something, have you considered checking hitInfo for what you're colliding with?
@marble halo You ought to be able to get to the name of the object via hitInfo.collider.gameObject.name
for some reason, when trying to read properties/keywords from a material, my script doesn't grab the latest ones (because i assume they are not saved / written to disk) until i recompile something (such as the script). i assumed it may be a problem with the material not saving (and i know calling saveassets is asynchronous but even if i call a wait it still runs into the same issue). i tried about every AssetDatabase, EditorApplication and EditorUtility function to see if i could try and force save before reading and i've gotten nothing yet. any one have any ideas :/
how do i have a game object thats attached to my character face the direction my player is facing? in this case i have an arm thats seperate from the capsule player and it kinda, well, looks in its own direction, so i wrote some code and it kind of works? the object faces in the direction im looking, it just does not actually rotate the arms fully with my character, here ill send a vid but heres the code
public class Orientation : MonoBehaviour
{
public Transform orientation;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 position = transform.position;
Vector3 direction;
direction = orientation.forward + transform.position - position;
transform.rotation = Quaternion.LookRotation(direction);
}
}
Iโll try that when I get back
To be clear, the arm isn't parented to the "character" or "player", right? Are these two words that represent the same object?
the arm is parented to the character, also heres the vid
wait why is that done as a file
ohhh do i need to convert it
Oh I see. This likely isn't really a code issue.
You could solve this in code, but the simplest solution would be to parent the arms to yet another child object so you have Player > ArmPivot > ArmModel in the hierarchy.
agreed
Let the child ArmPivot rotate and use the child of that child to offset your arm forward into your view.
ohhhh
so create empty --> armpivot then drag my arms into that
and parent the armpivot to my pc controller
Yes. This is a good habit to get into whenever you're setting up rigs or camera dollies.
Frankly, if all you need is to have your hands follow the pitch of your camera, you shouldn't have to control the yaw rotation of your arms at all; can't they just rotate with the parent capsule? @hollow dust
i tried, albiet before the new parenting stuff and it kinda just kept facing one way
Capsule rotates with yaw, ArmPivot rotates with pitch. The arms are actually a further child of ArmPivot. You might be able to simplify all of this.
i got it kind of working, it just only does it backwards lol
dw
i can fix it on my own from here
tysm!!
Just to make sure. when setting a variable. the difference between public and private is that public allows me to acces that variable in other scripts and private makes it exclusive to that script
also i can edit the variable in the inspector. right?
Exactly.
yep! but if you want a variable to be private but still accessible in the editor use [SerializeField]
oh snap THATS what serialized is for
oh so its private i ust wanna edit it in the inspector without having to go back and forth to the code? Do people leave it serialized of just when they are developing
[SerializedField] is useful if you want to be able to modify the data but don't want other objects in your game to be able to reference the data through scripts. Those private fields aren't accessible by other objects.
The reason this works is because [SerializedField] has the secondary effect of making the field read/writable by Unity's design-time tools. The inspector sort of doesn't care what is public or private, but happens to treat any public data on components as serialized anyway. There isn't much rhyme or reason to it. You the user aren't what public/private keywords are trying to protect your objects' data from anyway.
ahhhh ok im starting to get it. before i know it imma be op in code like you
Think of it like this: the inspector greedily serializes anything public because, since it's public, there shouldn't be any harm in doing it.
im learning about simple types now. I did mugen for years so variables are entirely new to me. Different is that our stuff was preset all we had to do was put in the number
https://www.youtube.com/watch?v=exqlMRLTESA Lemme plug, then.
In this video, we get right into all the fundamental (primitive) data types used in C#.
00:00 Intro
00:17 What is Primitive Data?
01:25 Integrals (Integers)
11:03 Initiation and Default Values
12:38 Nullable Types
13:36 Integrals Not Covered
15:18 Floating Point Numbers (Reals)
18:12 Precision Demonstration (In Unity)
22:37 Char Type
23:46 Tupl...
Also, what I say at the end about string == char[] is only partially true as strings are immutable in C#. I'm going to reupload this video with corrections in the next day or so.
oh nice. you did a vid. let me check it out and save it to my learning playlist. TYSM!!!
Very nice! Feels like I'm watching rust tut ๐
One suggestion would be to show the website where value type's domain is displayed as a table struct - as well as a link reference to the documentation for user who wants to read more into! @earnest epoch
Yeah, that would be good to mention. I tend to be a bit scatterbrained when trying to talk/think/type.
Do express yourself, because eventually you can edit your video. It's fun to edit your footage to help deliver contents clear and informative.
hi! i'm trying to implement my own version of the vertex lighting parameters for unity_LightAtten. the docs claim y is 1/cos(spotAngle/4) but this cannot possibly be right.
i've plotted out a bunch of bunch of spot angles and their values grabbed from the frame debugger below. spot angle is on the left
{179, 1.4256}
{170, 1.538174}
{160, 1.688059}
{120, 2.732051}
{105, 3.470881}
{100, 3.794776}
{90, 4.613126}
{80, 5.75877}
{70, 7.431356}
{60, 10.00997}
{50, 14.28811}
{40, 22.16552}
{30, 39.18637}
{20, 87.81952}
{15, 155.9076}
{11, 289.6719}
{10, 350.4453}
{1, 35025.5}
unfortunately i dont think the source code is available for the built in pipeline or whichever part of the codebase actually calculates these variables so i can't just go check
anyone have any ideas?
Hey Team, I am trying to make night club laser, What I have is a line render and with that, I was told to use Partical system. How ever with saying that, I am trying to make more then one laser beam and something that looks some what real. This is my code so far.
using UnityEngine;
using System;
public class LaserController : MonoBehaviour
{
public float laserLength = 50f;
public float laserDuration = 0.1f;
public Color laserColor;
public float fireDelta = 0.5F;
private LineRenderer lineRenderer;
private void Start()
{
Debug.Log("this is working");
lineRenderer = GetComponent<LineRenderer>();
lineRenderer.material.color = laserColor;
lineRenderer.enabled = true;
}
private void FireLaser()
{
lineRenderer.enabled = true;
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, transform.position + transform.forward * laserLength);
// Adjust the laser light range based on the laser length
Invoke("StopLaser", laserDuration);
}
void Update()
{
float[] spectrum = new float[256];
AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);
for (int i = 1; i < spectrum.Length - 1; i++)
{
float tmp = spectrum[i] * 5;
if (tmp >= 1.2f )
{
FireLaser();
}
Debug.Log(tmp);
}
}
private void StopLaser()
{
lineRenderer.enabled = false;
}
}
so this code is listening to a audio track, for its highs, once done so. it will trigger the lasers.
But my lasers are not looking like lasers, I am not sure how to get the partical system to work with the line render
This is what i have
to make them look "laserish" you'd probably want to:
- give them an emissive material
- use the Bloom postprocessing effect
hmm alright ill give that a shot, so that should add light to it right, now this is in a 3d template, I am not in a universal pipeline. would that still be ok, or would it not show correctly ?
i have no idea what your project template has to do with anything other than the fact that the different render pipelines have different postprocessing frameworks
you'll want Bloom either way.
ahh alright, thank you for the advice ๐
I'm trying to make a survival horror game in which the player searches through a randomly generated assortment of rooms, however I keep getting an error that "NullReferenceException: Object reference not set to an instance of an object Generator.Start () (at Assets/scripts/Generator.cs:111)". Here is the pastebin if someone would like to take a look: https://pastebin.com/ASM7vaqx
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.
Main issues seem to be from 105 - 120
connectorRoom.GetComponent<Room>()
must not have a Room component
Your error literally tells you where the issue is(line 111). You don't need to guess...๐
Alright, I have got something working and it is looking really good, now to add more lasers to one component
p = new Paragraph(string.Format("xxx - yyy : {1}", 0, 9));
p.Alignment = Element.ALIGN_CENTER;
document.Add(p);
Friends, I have such a code snippet. But this prints plain text to the pdf file. I want to make one image print of it. How can I do it ?
is the "Room" component not the same as the class defined at the beginning of the script?
It probably is, but it doesn't prevent it from not being on the gameObject.
Welp the problem was that I named the script something i shouldnt have thanks for your help thouhg
Script name and class name are 2 different things. Although they have to match for a MonoBehaviour to work propely
You enable looping in the animation import settings. As for making it play when moving, it depends on whether you're using the animator or something else.
yes
Animation import settings. Not the animation component.
For that, you should do the beginner pathway on unity learn. Or read the manual.
you'll be back for another fish though
Nope. We don't appreciate people that don't put the effort here.
I feel like you didn't look at the manual after all...
I'm saying that if you did look in the manual, you should know the answer.
Where the manual is?
google "unity manual"
!manual
๐ The Unity User Manual helps you learn how to use the Unity Editor and its associated services. You can read it from start to finish, or use it as a reference https://docs.unity3d.com/Manual/index.html
Hey, I have a UI button that triggers an upgrade for an object in my game, however for some reason when i press the button the function that it activates runs twice. is there any reason for this?
Here is my code for the listener
rangeButton.onClick.AddListener(RangeUpgrade);
And here is my code for the upgrader
public void RangeUpgrade()
{
print("Range upgrade executed");
if (statsManager.money >= rangecost && rangelvl <4);
{
statsManager.money -= rangecost;
rangelvl += 1;
print("range lvl ="+rangelvl);
print("money ="+ statsManager.money);
}
}
if it runs twice, you either click it twice, or you subscribe twice
(subscribing twice can include not unsubscribing when you should, and leaving something subscribed where it just gets called again)
so i should have a bool that activates when the button is pressed and run the code through that?
or i change the buttons interactability
No, just make sure you subscribe only once? And any time your objects are destroyed make sure you call RemoveListener
oh alright, thanks!
IEnumerator CalculateTrajectory(Bullet bullet)
{
print(bullet.forwardDirection);
while (true)
{
bullet.flightTime += 0.1f;
bullet.lastPosition = bullet.newPosition;
CalculateYDev(bullet);
CalculateZDev(bullet);
bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
//print(bullet.newPosition);
//bullet.newPosition += bullet.forwardDirection * 100;
Vector3 direction = bullet.newPosition - bullet.lastPosition;
//print(direction);
float distance = direction.magnitude;
print("Before" + direction);
direction.Normalize();
print("Normalized" + direction);
if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
{
print("Hit.");
}
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
//Debug.DrawRay(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Color.red, 15.0f);
bullet.forwardDirection = direction;
yield return new WaitForSeconds(0.1f);
}
}
Trying to make a raycast ballistic system where bullets have no real object, and are only class instances. My main problem is that my ray is not shooting in transform.forward, but instead in the global z axis. Any help?
Sorry if you've seen this again, I still haven't worked it out.
Is that debug ray what you're referring to?
Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
Yes
The way you move the bullet is very weird. Can you explain the logic behind it?
bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
Also, why the y z axis and not x?
Why not just add a vector?
z axis is forward axis
Why?
Because it's the forward axis generally?
ummm
transform.forward is in the z axis
if you're talking about local space, yes
does that mean that newPosition is in local space?
transform.forward is not in the z axis btw. That statement doesn't make any sense
https://docs.unity3d.com/ScriptReference/Transform-forward.html
It states: Returns a normalized vector representing the blue axis of the transform in world space.
Yes, that is correct. It tells you that transform.forward aligns with the local space z axis. But it's not the same as transform.forward is in the z axis
that's just being pedantic
And what's more important, raycasts take world space, not local space.
No, there's an important distinction that is the key to solving your issue.
Since you're dealing with "imaginary" objects without resorting to any local-world space transformations, there's no point at all in using the local space.
just started Unity a day ago and i am lovely it, honestly switching from roblox's lua to C sharp is annoying but its really funny ngl.

I've got a bit of a silly question about best practices
If class A makes an object of class B
And class C needs to access said object
and now:
- should it get a reference to class A, and get the public reference to the object through A.bObject
- should class A get a reference to class C, and call something like C.GiveReferenceToBObject(bObject)
- should class D create the object B, and both classes A and C have total access to it?
- Should class C do something along the lines of
this.bObject = a.bObjectand use that?
As of right now, there is only one instance of B
Which means that option 4. seems to be the best
But, it is possible that in the future, B will be replaced by another instance of B, at an arbitrary point in time
which points to other options
How concerned should I be with the possibility of it happening?
I'm conflicted
On one hand, option 4 seems to be the simplest and cleanest option which is good, but on the other, making it so that class C has to be modified when changing class A is a bad practice
I am not sure if this is the right place to ask, but I don't know where else I should go
Is that a quiz?
Option 2 seems like the one that would lead to the cleanest code in my opinion. But it also depends on the relationship between these 3 classes.
it depends on the situation. assuming an object of class B is created at an unknown time after objects of class A and C already exist, depending on the complexity of the object being created, you might need a separate builder class (class D) that creates class B. it would then be the responsibility of that builder class to update whatever needs to be updated
It's not a quiz, I'm just thinking about a situation I had a couple of days ago
But what if more classes need to use it down a line?
Keep an array of classes inheriting from interface iNeedsBReference in class A?
I'm trying to figure out a general good approach
but this is a pretty vague answer because again it really depends on your situation
But then again, this could lead to just more and more builder classes appearing left and right, every time this situation happens
Which is introducing unneded complexity to a simple problem
You need to clearly define the relationship between these classes first. Then the answer should be obvious.
unfortunately, complexity and modularity/decoupling go hand in hand. but yes, any solution to any problem will introduce some complexity, which varies depending on how much abstraction you want to introduce
I'll be honest, I don't exactly remember the original situation that has caused this question
So right now, I'm thinking of a best general situation for this type of problem
So the question now is, how to decide how much abstraction is needed for a given problem, in order to be reasonably future-proof and ready for change, but without making it overly complex
Which is surely a super easy question with a simple answer
...great
You two seem to be more experienced programmers than me
How do you even deal with situations when it comes down to a question as general and with no answer, as this one?
Because at this point I am tempted to roll a die on a case by case basis, when I have absolutely no clue what to pick
The general solution is to define the relationship between the classes. There's usually a hierarchy(tree) of relationships. The dependencies should usually be between a 2 type linked in the hierarchy(parent-child). Ideally it should also be 1 sided dependency. But then again, not all cases have to follow the same rule, that's why it's important to consider the solution within the context of the problem.
You usually start with a specific case, then extrapolate from it and see if you can apply some common pattern to more cases.
if anyone has an idea how to fix this problem please tell me asap:
I have a URL for a unity web request... i need to change a part of it...
so far I have been using _url = originalString.Replace("oldValue","newValue");
but when I send the unity web request i get "malformed url"... how can I solve this please (if something is wrong with it)
please keep in mind, when i write the new url into my web browser the result is correct... I get the result I want
But overall, I guess it comes with experience. The more different cases you have worked on in the past, the easier you are to come up with some solution to a new problem.
That's what I usually do, it's a really common problem
It's just that last time, I happened to reach a situation that was basically as similar to the abstract representation as I provided, as possible, so I was honestly lost
I suppose that is what it ultimately comes down to
There must have been something non abstract about it though. You'd never have classes named "A", "B", "C" in an actual project.๐
Will need to share some code and the actual error.
I will share the code but there are no errors
Well, yeah, but the classes had nothing else in common
Which points to the solution with class D, but as I said there are problems with it too, and B was just a random dictionary
No clue which project it was even in, let alone what part of it, so yeah XD
I'll remember to save it next time it happens
This is not an error though. It's a log from SendSMS. Is that your script?
Lmao thought that was to me for some reason, oops XD
yes.. I am sending a unity webrequest and debugging the www.error if my request's result isn't a success
Wdym by "had nothing in common". Why would they need to reference each other then?
If they have a dependency, it means that they have some kind of relationship
Except for that one dictionary
What dictionary?
async Task<byte> SendingBadSMS(string phonNumber, string message)
{
//string _getUrl;
string stupid = "https://website.something.com:8002/api?username=asfasfasf&password=asfasfasfasf&ani=QuickShare&dnis=919000412202";
string _getUrl = stupid.Replace("919000412202", phonNumber);
Debug.Log(_getUrl);
using (UnityWebRequest www = UnityWebRequest.Get(_getUrl)){
//sending
UnityWebRequestAsyncOperation task = www.SendWebRequest();
while (!task.isDone) { await Task.Yield(); }
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
return 0;
}
else
{
Debug.Log("Text= " + www.downloadHandler.text);
Debug.Log("downloadHandler= " + www.downloadHandler);
return 1;
}
}
}
That's the point, I don't remember now :/
I guess I'll report back if I have a more concrete situation than this
the www.error IS malformed url... but if i copy and past the same url into the webbrowser it works perfectly
What does the Debug.Log(_getUrl); print?
int[] sarr ={1, 2,3,4};
if(val.Contains(sarr)
{
}
the link that I post into the web browser
Getting how do I fix this?
fix what? Your code that shouldn't compile?
Fix what? There are multiple compiler errors there
im getting these errors when trying to building the project
anyone who has experienced those?
Don't you need to send the request? www.SendWebRequest();
As they do in the example here
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html
I did send it... sorry forgot to include that in the code snippet...
Okay, then there must be something wrong with your url. Perhaps there are hidden character, like line breaks or something.
You should post the log you get in the console, maybe it's not correctly URL-encoded
Like a space in the middle that should be converted to %20 or somethin'
the url works perfectly fine when I post it in the web browser.... no errors or anything
how do you get phonNumber
Your browser converts the URL for you as you submit it, not Unity
It might be stripping out characters
ok how do I convert my url
No wait
When you copy the url it might omit line breaks and stuff.
You first ensure that the value you get in Unity is correct
IT IS 100%
You keep saying that with 0 proof
.
I'm betting on the following:
the phone number is retrieved from an Input Field's underlying TextMeshPro component, instead of the InputField itself
we tested it before using a specific number and it worked, now even if i change this number to that one it wont work
Cool, how do you get phonNumber?
ther's no tmp component or any input field... just a function reading a csv file
Okay finally more info
That could be reading line breaks as well
You should loop over the string, and print out each char value, and check that there's no control characters
At least check that the phonNumber is the length you think it is
why does NO ONE BELIEVE THAT I KNOW HOW TO TAKE A LINE WITHOUT TAKING ANY MORE LETTERS
Yeah if you "see" 10 chars, but num.Length returns 11, something's up
๐คฆโโ๏ธ
i made sure of that too
How do I check if an int array contains a sequence of numbers?
Then just say so instead of being a prick about it??
i dont think the problem is the computer ... i tested the number of letters and everything
Eg
How do I check if int array contains these values {1, 2,3,4}?
Do you know how to use the VS debugger? You should use that now to go through the code line by line and inspect the variable's contents. Can't be of more help, if you think the data is correct but Unity says that it isn't, then the data isn't correct
ill do that
thanks
I want to check if it contains the values or not
Not check sequence
For eg
My array can have {1, 2,3,4,5,6,7,8}
I want to check if my array contains {2, 3,4,5}
It would generally be easier if you used a HashSet, which has a Contains function that does this sort of thing quickly
I checked hashset
But Idk how it can be implemented in this scenerio
iterate over your array and check whether the item is contained in the set
I want to check for multiple elements tho
Like check for elements {2, 3,4} in an array having {1, 2,3,4,5}
Iterate over your array and check whether the item is contained in the set
For each element, is it contained in the array? Yes - continue to the next element ; No - the array doesn't contain all the expected elements
You probably have a probuilder editor-only asset included/referenced somewhere in your scene/prefabs
I have an array val
int[] val = new int[5]
val.Sort()
Is not working
What's not working?
I would google how to sort an array in C#
Oh, the message above is the error?๐
how can i look for what asset is editor only?
Well, it's mentioned in the error: MeshFilter Icon. Try searching it in the hierarchy.
so i should search "t:MeshFilter" and then? I already looked for each object that has a mesh filter but i dont find labels like "Editor Only" or similar
MeshFilter Icon
not a mesh filter
The assets in question is called MeshFilter Icon
It's probably a sprite..?
i looked for all my ui objects and nope
they only use things like UISprite or Checkmark sprites
Welp that's what the error says.
make sure none of the sprites are unity/probuilder default resources
You can't use them in a build.
Well, some of them. Some of them could be editor only
In general it's a bad idea to use built-in assets.
yeah i know
i was so bored to create them
it uses a mesh filter icon, that is the icon that is used on the ProBuilder Mesh Filter component on some of my gameobjects in my scene, so maybe is that the problem?
That's literally the name I mentioned like 3 times. ๐
And it's in the error too.
The assets in question is called MeshFilter Icon
Well, it's mentioned in the error: MeshFilter Icon. Try searching it in the hierarchy.
Did you just ignore what I was saying?
Hey I was wondering if anyone could help me with this. Sometimes my character (when theres a lagspike) shoots forward/left when running or walking. Weird things like this keep happening.
That's the move script
Im using blend trees btw for the animations
And this is the input manager
https://paste.md-5.net/safurexavi.cs
I've been stuck with this for so long and idk how to fix this. Any help is appreciated
nono, i was just excluding that because i have not assigned that icon to one of my sprites like buttons or images
thats it
but now im removing every reference to unity built in sprites
anyways thank you
Ah, okay.
There's no off-topic here.
Ok, but how is that relevant to this channel?
Is anyone aware of issues related to use of local functions with unity? Such as possibly leaking memory
Not inherently, no. You could certainly leak memory in such a function though.
I don't know what local functions has to do with unity specifically, neither do I understand how they would be more prone to memory leaks than regular functions...
Well, for example I know some historical versions of mono would generate garbage though not necessarily leak it, on some platforms with local functions. It also just wasn't supported on some console platform builds of mono
But atm I'm experiencing what looks like a memory leak, possibly native memory, after having added several local functions which enable and disable entities with rendering components
And other material property setting stuff.
Anyhow thanks for the response. I'm happy to keep using them if I can
Hey all. I have a small problem concerning one of my gameplay mechanics. I have a script, which enables gameobjets to attach to each other in order to form a burger. It works perfectly, except for the fact that a base will attach itself to gameobjects that aren't already apart of a burger. I don't understand why this happens, as I've added code that should prevent this from happening. Please help!
https://gyazo.com/9761dd0e2877b2f959743f2fec5a5b17
Here's the script: https://pastebin.com/PjamEJRw
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.
anyone know a way to optimize a scene with a lot of points?
im trying to create the chaos game in unity but i need to have about 2 million object to get an accurate image
maybe 200,000
only problem is it slows unity down a lot
for context its basically just a way of creating fractals
You should create them dynamically (or resize/reposition existing objects) as you zoom in and out
Rather than trying to show them all at once
That's way too many objects
You could also look into drawing this with a shader or something instead of individual objects
is it possible to check if a collider collided with more than 1 object?
Everything is possible
how can i lerp the rotation of an object so the x and z returns to 0 but the y rotation stays the same ? i tried it like thi but it doesnt work
can you provide a link if you have one? I think I cannot search properly
You're confusing Quaternion.y with a y Euler angle
You should not ever be touching the xyzw of a quaternion basically
They are not euler angles
so i shouldnt use quaternion.lerp ? i tried that it looked like this but it still rotatet the y axis
You can use quaternion.lerp, your problem is your attempt to use transform.rotation.y as if it's a y axis rotation which it is not
Now in this new screenshot you're making the same mistake again
With rotation.x
ah thank you so it would be transform.eulerAngles.y ?
Those are not euler angles and you should stop trying to use them as id they are
Sure but there's better ways than converting everything to Euler angles
thank you, i hate quaternions and rotation stuff
void proceduralGen() {
noiseMap = new float[height, width];
// Generating random float value to use as seed
float randomFloat = UnityEngine.Random.Range(0, 10000000f);
// Checking if useRandomSeed Boolean is true in the inspector
if (useRandomSeed) {
// public int seed variable
seed = randomFloat;
}
System.Random pseudoRandom = new System.Random((int)seed);
// Offset to add to Perlin noise
float offsetX = randomFloat + 100f;
float offsetY = randomFloat + 200f;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
float xCoord = (float)x / width * scale + offsetX;
float yCoord = (float)y / height * scale + offsetY;
noiseMap[x, y] = Mathf.PerlinNoise(xCoord, yCoord);
// Add randomization to the Perlin noise
float randomValue = (float)pseudoRandom.NextDouble() * 2f - 1f;
noiseValue += randomValue * 0.1f;
// Edge of the map is water
if (x == 0 || x == width - 1 || y == 0 || y == height - 1) {
map[x, y] = 0;
} else {
map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercentage) ? 0 : 1;
}
}
}
}```
so i wish to make a 2d island using cellular automata and then use perlin noise fill the island with biomes i have got 70% of the code working but i want to add a **seed** for ths where the shape of the island and all the biomes within the island stay the same when i insert the seed but i dont whats wrong with my code here
and it doesnt generate the biomes proprly
and the biomes dont stay constant with the seed
a powerful website for storing and sharing text and code snippets. completely free and open source.
this is the entire code for my script
Hello, how can I make interface operations asynchronously in my game in Unity, I want to do it as fast as I can, what is the fastest way you know
What do you mean by interface operations exactly?
I am a plugin developer in a unity game and I can do interface operations in the main threade, that is, just interface operations, changing the text content, etc. In order to do this, the game provides me with certain functions, which method can I call them in the fastest way.
I'm still not really understanding what "interface operations" means
Are you just talking about calling the Unity API functions?
There's no fast or slow way to call them
There's only one way
User Interface maybe? Or C# interface?
You can't be any faster because there's only one way of changing what you want, and those are already optimized
Like a TextMeshPro Text that will only redraw the text in the game if it changed
Pass the same string 10 times and it'll only perform a redraw once, the first time
Let me rephrase my question, how can I run my method on the main thread as fast as possible without occupying the main thread?
guys i want to change the position here how do i do that ?:
Instantiate(projectile, transform.position, Quaternion.identity)
should i do:
Instantiate(projectile, transform.position = 93 12 43, Quaternion.identity)
?
new position
Run it on the main thread. You cannot get faster than this, because you cannot offload the work to another thread, as Unity doesn't like that
wdym ?
Okay, I understand that, but I have one or two questions for you.
like:
Instantiate(projectile, transform.position,new Vector3(x, y, z), Quaternion.identity) ?
'Task mymethod = domethod(arg1,arg2);
await Task.run(async() => mymethod()') when I run it this way the result is much faster but
await domethod(arg1,arg2);; why do I get a slower result
I don't understand asynchrony very well, can you help me a little bit?
ok i will try ty for your help !
Rigidbody rb = Instantiate(projectile, new Vector3(-0.001, 0, -0.0114), Quaternion.identity).GetComponent<Rigidbody>();
like this right
Try it
because it told me in the debug that they cannot convert from 'double' to 'float'
Yeah but you said "will this work" but you already tried it and knew there was an error
no the error just popped
Instead say "I got an error, here's my code, here's the error"
after i inserted the code
Alright. In Unity you need to add f at the end of decimal numbers so they're interpreted as floats. Example 3.14f
ty so much now it works
I'm writing a dependency injection framework, and I am having some troubles figuring out the right builder pattern.
RegisterDependency<TDependency> returns a DependencyBuilder<TDependency>.
I can then stack build statements onto that call like so:
LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId");
Now normally you would do a Build() call at the end to check if the required parameters have been passed in the earlier calls, but I am looking for a way to make that happen automatically.
How do I make the builder call a check function at the end of these stacked calls only, without making that specific end call? the syntax here would look much cleaner if I could leave out the last call here ``LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId").NowActuallyRegister();`
I asked chatgpt and it came up with implementing IDisposable and then registering my dependencies like
using (var builder = LocalContainer.RegisterDependency<string>().FromInstance(someStringDependency))
{
// Do something with the builder
} // Dispose will be called automatically at the end of the using block
but that seems silly, as i dont need to have access the builders anymore and a seperate using block for each dependency is very user unfriendly.
Does unity have a filedrop callback or is there any way I can get the functionality for it?
did you see my reply from earlier ?
Wait, Nevermind, I think I misunderstood something.
there is no built in method in unity for drag n drop
If you assign the DependencyBuilder<T> to a variable of another type after you set it up, you could make an implicit operator to that target type, and put your checks and build code in it
But I wouldn't recommend as it's not clear on when the build actually happens
I'd stick to an explicit Build() method
yeah the problem is I don't really want to treat the builders as variables at all
the problem I have with that is that if you forget the call to Build() it wouldn't throw an error right away, but the dependencies wouldnt be reigstered either.
now you can resolve that by for example returning something from the Build call and then checking if the value is returned
but that would again make the syntax of registering my dependencies more complex
rotatetowards? slerp?
worst line of code I've written so far:
if (UnitManager.instance.soldiers.Find(x => x.index == buckets[(i) * sideTiles + j][i2].index).unit.team == soldier.unit.team)
Hm, how about how Microsoft does it for their dependency injection framework? Like they call a method that takes in a lambda with a service provider as a parameter. Register your stuff to that provider in the lambda's body.
Then once the lambda finishes, internally run it
but this one takes an axis as an input and an ammount to rotate it arround said axis how would i do that with slerp
I want LocalContainer.RegisterDependency<FooBehaviour>() to throw an error
LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour)
to be the minimum
and then have optional builder stacking like be allowed
LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId")
mind linking that?
this one is also pretty ugly but not as bad
sorter.distance = (buckets[(i - x) * sideTiles + j + y][i2].transform.position - soldier.transform.position).sqrMagnitude;
normally it makes sense that you would call a final Build() or whatever if you need to actually do something with what the builder returns, but for this framework syntax it makes it weirder
oh do you mean you want to only do it by specified amount?
that gives me PTSD from rotation matrices
I don't have a link but it's common to see this kind of stuff
Builder.Services.AddDatabase(configure => {
configure.UseSqlServer();
configure.UseConnectionString("...");
});
Then once the lambda is executed, it internally checks that all values were provided, and throws if needed
yes and only arround the local forward axis
eg:```cs
Quaternion startRotation = transform.rotation;
Quaternion endRotation = transform.rotation * Quaternion.AngleAxis(-angleDifference, transform.forward);
float t = 0f;
float rotationTime = 0.5f;
while (t < rotationTime)
{
t += Time.deltaTime;
float normalizedTime = t / rotationTime;
transform.rotation = Quaternion.Slerp(startRotation, endRotation, normalizedTime);
}```
this does smooth the rotation but now it does not only rotate arround the local transform forward it sometimes rotates arround all directions
is there a way to use the local forward axis ?
transform.forward should be local
wait, ill try to record what happens
if it wasn't it would just be a Z axis unit vector
it behaves really weird but i think i can replace all the code with two joints
i was wondering if in this channel i can ask about mirror and fizzy steamworks coding or if thats another channel
Hey guys, Iโm making a 6dof flight system, but want to have players able to walk around the ship, and for ai to be able to pathfind in the ship. Iโve kind-of settled on two solutions:
-
The ship the player is on stays completely stationary and at the origin, while the rest of the universe rotates/moves around it, but this has the issue of not really being able to make collisions work
-
Parent player characters to the ship theyโre on and actually move and rotate the ship, but this seems to have the issue of probably not being able to get ai pathfinding to work (though I havenโt really tested it yet, this is just intuition)
Any advice on which one I should do?
In the past I took solution 1 and found it really easy to get started. Moving rigidbodies (the player) around a moving ship comes with a lot of problems in itself.
With solution 1 (which is the one Iโve got) itโs pretty painful to get the skybox to rotate correctly, and Iโm honestly not sure how I would make the players ship collide with stuff
Also does it change anything if Iโm not using a rigidbody character?
You could feed rotation data into a skybox shader to spin it properly
Iโll have to play around with that but seems much more sensible than what Iโm doing
With solution 1 if your obstacles have rigidbodies it's possible to have collisions but your ship would never move out of the world origin
` public Text scoreText;
int score = 0;
// Start is called before the first frame update
void Start()
{
scoreText.text = score.ToString() + " Collisions";
}`
I mostly just read that there was a collision and either destroyed/damaged and stopped my ship but I bet you could work out some way to do better collisions
Hm, Iโve tried adding rigidbodies to the obstacles but my ship just phases through them, would it be possible to make the ship bounce off of them?
but it says there is a nullreference exception at the line in VOID start
See if OnCollisionEnter is called on your ship
im only shifting things, i left the object rotate normally.
keep track of how your universe is rotated/shifted, that makes it easier to adjust objects properly.
if you know what your "universe rotation" is, you can just copy that to the skybox
Yeah, I think i need a custom skybox shader to be able to rotate in more than one axis though
You could set it up in Shadergraph with a Vector3 as a property, it shouldn't be too difficult once you get all of the axis to match
You do lose some features because of that though because it will be your own skybox shader. So it would be a solid color unless you mapped a texture to it
๐ many thanks
There will still be plenty of problems in the future but it's a step haha
also, i keep track of the scenes absolute universe postion with a double vec3, instaed of float3, because the floats with their precision issues where the cause for the whole ordeal.
//TODO: nicen up
float targetFront = 0;
float targetBack = 0;
DebugExtension.DebugWireSphere(raycastAnchorPlane.position, 1f);
if (Physics.SphereCast(raycastAnchorPlane.position, 1f, -raycastAnchorPlane.transform.up, out _, 1f, ~steeringRaycastIgnoreLayer))
{
Debug.Log("Grounded");
TorqueUpright(relativeSurfaceNormal);
//Vector3 axisInRaycastPlane = raycastPlane.ClosestPointOnPlane(axisBack.position);
//Vector3 axisInAgentBodyPlane = agentBodyPlane.ClosestPointOnPlane(axisBack.position);
agentBody.AddForce(
agentBody.transform.forward * agentController.moveAxis.z * 5,
ForceMode.Acceleration
);
targetFront = steeringParameters.axisMaximumDisplacement * agentController.moveAxis.x;
targetBack = -steeringParameters.axisMaximumDisplacement * agentController.moveAxis.x;
}
axisFront.transform.localRotation = Quaternion.Euler(0, targetFront, 0);
axisBack.transform.localRotation = Quaternion.Euler(0, targetBack, 0);```
anyone have an idea why my spherecast here does not seem to be true whenever I touch the ground ?
i have to awkwardly shuffle around over it for it to register
the white sphere is the spherecast
no the plane is not on the ignore layer
ah overlap sphere seems to be the choice here
someone know why Bolt setup dont finish?
if i click generate it doesnt work and in visual scripting appear this:
Does a unity crash saying invalid scene handle, in a variety of different callstacks, usually actually trying to allocate memory either with physics or in renderables (ie, mesh geometry allocation), mean anything to you guys? My thought is that we are doing a lot of touching of entities off the main thread which is known trouble, but would it exhibit this sort of error? And secondly is there any sort of global hook for being notified or asserting when an entity is activated deactivated or it's scene changes or this sort of thing?
!bug
๐ชฒ 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
?
It's the game that is crashing, not the editor. If that is suppose to be for my benefit
Report as bug
Why would I do that every time my game crashes?
someone know why Bolt setup dont finish
Just out of curiosity, the way we're doing it right now is having an actual physical box around the player with the skybox texture on it, and rotating that. Is there anything inherently wrong about that method? Should we write our own shader instead anyway?
Does anyone know how I can make it so my text replaces the old text and the old text keeps it font?
I'm trying to make it so it seems like the mc is understand ancient text.
https://gdl.space/tumodocuro.cpp
nvm, skybox reflections are gonna be messed up with our current method, i'll try to figure out how to make a convincing skybox shader :p
With TMP Rich Text tags
tmp.text = "This is in the default font. <font=\"FontName\">This is written in another font.";
You need to displace the <font="Font Name"> tag through the string as the text changes
Hello, I had an idea that I suspect will be above my skillset but wanted to give it a try anyway. So I'm using a third party asset called DoTween in my project to control the way certain objects move around.
I have recently learning about adding a layer of abstraction and wanted to give it a go. So that if DoTween ever goes under or I want to switch to a different system I only have one place to do this inside of.
Some of the use cases are easy like DoMove(amount to move) I can make my own method called MyMove which will just call DoMove.
Things get trickier with callbacks though, this is when doTween allows me to call a method on my script after a move has happened like this DoMove(amount to move).OnCompleted(method to call)
If I'm calling my own static MyMoveManager script how would I pass it my method on my current class ? Something like this maybe?
My Class:
MyMoveWithCallBack(Action callback, moveAmount)
{
DoTween.Move(moveAmount).OnCompleted( callback)
{
Extension methods would be a good way of doing that. DOTween itself uses extensions for all its methods.
public static void MyMove(this Transform t, Vector3 move, Action callback)
{
t.DOMove(move).OnComplete(callback);
}
Then you can just call it like that: transform.MyMove(Vector3.right * 10, () => Debug.Log("Complete!"))
Can anybody see why this array keeps wiping itself? I'm baffled.
Debug.Log("Drop down.");
oneWayPlatArrayCached = oneWayPlatArray;
if (oneWayPlatDropActive) StopCoroutine(oneWayPlatDropCoroutine);
StartCoroutine(oneWayPlatDropCoroutine);
private IEnumerator OneWayPlatDropCoroutine()
{
oneWayPlatDropActive = true;
IgnoreArrayOfCollisions(true, oneWayPlatArrayCached);
yield return oneWayPlatDropInterval;
IgnoreArrayOfCollisions(false, oneWayPlatArrayCached);
oneWayPlatDropActive = false;
}
void IgnoreArrayOfCollisions(bool ignore, Collider2D[] collider2Ds)
{
for(int i = 0; i < collider2Ds.Length; i++)
{
if(collider2Ds[i] != null)
{
Debug.Log("Collider is named " + collider2Ds[i].name);
Physics2D.IgnoreCollision(box2D, collider2Ds[i], ignore);
}
}
}
Only the first IgnoreArrayOfCollisions() outputs a Debug.Log, and the collisions are never reenabled.
'Drop Down' only appears once in the console, so it's only being called once. I'm really confused.
Wow thanks SPR2 that's really clever!
I actually used my first extension method recently (to shuffle lists) so it sounds like a perfect solution. I wasn't sure the Action would be the right type for the callback so I'm glad I got that right.
I'll play around with this and let you know how it goes, cheers!
I have a coroutine which is running for some reason even after I stop it (and the bool that makes it get called is also set to true(which means it wont get called))
Here's my code (The coroutine IEnumerator Rotate): https://pastebin.com/itSEQqe8
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.
The game shouldnt crash, 99% of the time. Unless you modified something low level, it is likely a bug
It should just throw an error in console and or Player.log
I've been trying to tackle on slopes for the past years creating this game. I am out of options and this is as far as I could go.
Here are the two functions that are used for walking:
public void Walk(float maxSpeed)
{
if(CanRotate)
{
CameraToForwardRotation();
}
if(!CanMove) return;
Vector3 wishDir = SlopeItUp(dir);
float acceleration = grAccel;
wishDir = wishDir.normalized;
Vector3 speed = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
if (speed.magnitude > maxSpeed) acceleration *= speed.magnitude / maxSpeed;
Vector3 direction = wishDir * maxSpeed - speed;
if (direction.magnitude < 0.5f)
{
acceleration *= direction.magnitude / 0.5f;
}
direction = direction.normalized * acceleration;
float magn = direction.magnitude;
direction = direction.normalized;
direction *= magn;
rb.AddForce(direction, ForceMode.Acceleration);
}
public Vector3 SlopeItUp(Vector3 playerDir)
{
Vector3 finalDir = playerDir;
if(OnSlope())
{
finalDir = Vector3.ProjectOnPlane(playerDir, slopeHit.normal);
Debug.DrawRay(transform.position, finalDir, Color.cyan);
// rb.useGravity = false;
}
// else
// {
// rb.useGravity = true;
// }
return finalDir;
}```
All functions are being called right, the ground check for slopes is right, everything is right, I think what's wrong is the actual calculation. I have no idea where I'm wrong here and why is it so slow to get back to running after stopping on a slope as shown in the vid.
i am once again going insane over this shit
i'll have to visit a therapist by the time im done with this
My apologies for posting this after your question, I'd love to help you if I had an answer but I need to ask this question.. V
Good evening! I need help with this error, I have been getting for days whenever trying to instantiate a player using Nakama multiplayer feature:
"spawnPoint.transform UnityEngine.UnityException: get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."
It's a spawn function so it can't be in start or awake, here's the code:
public void SpawnPlayers(string matchId, IUserPresence user, int spawnIndex = -1)
{
Debug.Log("Spawning players..");
//If the player is already spawned, return.
//if (players.ContainsKey(user.SessionId)) return;
//Define a spawn point for the player.
GameObject spawnPoint = spawnIndex == -1 ?
spawnPoints[UnityEngine.Random.Range(0, spawnPoints.Length - 1)] :
spawnPoints[spawnIndex];
bool isLocal = user.SessionId == localUser.SessionId;
var playerPrefab = isLocal ? networkLocalPlayerPrefab : networkRemotePlayerPrefab;
player = Instantiate(playerPrefab, spawnPoint.transform.position, Quaternion.identity);
if (!isLocal)
{
player.GetComponent<PlayerNetworkRemoteSync>().NetworkData = new RemotePlayerNetworkData
{
MatchId = matchId,
User = user
};
}
players.Add(user.SessionId, player);
Debug.Log("Adding the player to the dictionary.");
if (isLocal)
{
localPlayer = player;
}
}
What's your question? Make sure SpawnPlayers is only called on the main thread like the error tells you. You are probably calling it in a constructor, but without any more context it's impossible to say for sure
since you're normalizing your direction, the horizontal component of the motion will be less and less as the slope increases. Try a very high slope, you'll probably see the character moves very slowly
that's alr bro ain't nobody gonna answer me anyway
oh somebody did actually
let me look into that
you're right..
My bad I didn't make it clear, so why whenever I add a breakpoint to the player = Instantiate(playerPrefab, spawnPoint.transform.position, Quaternion.identity); line and hover over "spawnPoint.transform" this error pops up: "spawnPoint.transform UnityEngine.UnityException: get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function." Resulting in no player prefab being instantiated. How can this be fixed?
now the question is should i be even normalizing the direction
are you accessing this from the main thread? It sounds like no
welp with no normalization the character shoots up with unreal speed
How would I know if I'm accessing this from the "main thread"? don't mind me I'm new to this
makes sense, you're applying the full force of the character's acceleration in +Y in that case
you still need to account for the y component, but the end calculation just shouldn't affect horizontal velocity
but it doesnt seem to shoot up only on the y, it seems like it shoots up on all of them
i might be wrong hold on
what does the stack trace look like? You should be able to use your debugger to look at active threads
One moment
So my grenade is calling on the take damage rpc but you dont take damage can someone help?
player file: https://hatebin.com/ivrdizjgto
grenade file: https://hatebin.com/qfdaqueuga
Do you mean those?
looks like whatever you're using for matchmaking is invoking this callback on separate thread
How should I invoke it in the main thread?
Or what is the main thread actually? I tried looking it up but couldn't understand
Is it something like this?
Maybe time to read up on threads. Yes something like that would work, or a script that checks a concurrent queue or something similar that you post work to. There are libraries to help also. What are you using for matchmaking? I would be surprised if it didn't address this, assuming it wasn't you that invoked the callback with Task.Run or something
This shit is weird as fuck tbh, I made it so it added the slope calculation to the actual direction and now it stops. I did enable the normalization again so maybe thats it???
I'll do, I'm using Nakama, I've read the documentation and watched their only few videos on the topic and I think nothing was mentioned regarding that topic up until spawning players because this was where I stopped since the error is occurring there
Would you recommend a better alternative for matchmaking besides photon? @mossy snow
debug your force vector. Did you forget to add the horizontal motion to it? You might also need to increase the magnitude of the y velocity you apply based on the magnitude of the xz velocity, otherwise next frame you might not have enough y direction motion if horizontal motion is high
no reason it wouldn't work, you just have to deal with some Unity idiosyncrasies
What does OnReceivedMatchmakerMatched look like? the docs for this library look like everything should be awaited in the main thread context already
I have this super simple game where your character just follows your mouse, but I think it would be fun to be able to control the character through your webcam by tracking your hand positionโis there a recommended plugin I should use for this kind of task?
hmm that looks fine, other than the lack of try/catch which maybe someday haunt you when you have invisible exceptions
is this an original idea?
I'm unsure what you mean by that
I created this game, so I think it's an original idea?
i mean did you copy an existing game you know of, or is this all you?
if its all you, you should 100% publish this (when its done)
I have that in mind, I'm just writing basic code for now
@mossy snow Have you tried Unity's Netcode, if yes what do you think of it?
currently I have a secret link on itch.io, but it's not published yet
I'd still like to add extra functionality, like the webcam hand tracking controls that I mentioned earlier
there are a variety of gesture recognizing libraries/plugins, you need to try them all to find out which one works for you, all of them are somewhat janky
that's why I'm asking for recommendations
i mean if you polish it to be a proper game (doesn't need much, think vampire survivors) this could be a meme game
it looks fun and is very easy to understand
are you calling vampire survivors a meme
I haven't, no
not normalizing the vector at the end produces this, no matter if on slope or not lmao
the recommendation is to try all
no clue if are you looking for visual feedback btw but just looking at this the skybox seems VERY bright for the rest of the game
something is insanely broken there Meta
noted
yeah this is the most confusing shit bru i tried to tackle this way to many times, the indomitable human spirit will prevail tho
how are you setting this vector
because uh thats a slightly large number
just slightly tho not like 10000000000x too big
its a debug.log of an addforce when i disable normalizing at the end of the calculation
lmaoo
there's no possible way I'm going to be able to "try all" (most of what I've seen is related to vr headsets, which is not what I want), is there at least a handful of plugins that are easy/popular?
I don't think any sane person would want to purchase every webcam tracking plugin in the asset store just to "try them"
make your own (real)
this is the actual calculation here, i removed the last direction = direction.normalized
not sure if youll get recommendations on such a specific thing here
better ask it on some kind of forum
oh, I see
@mossy snow i changed some things up, now the z and x are right (they are the same on normal ground), but the project on plane decides to make the Y 11 and not 30 as it should
I've seen this, but I am not sure how useful the resource is. https://www.youtube.com/watch?v=RQ-2JWzNc6k Most things I found are expensive, external hardware (Leapmotion, VR controller, AR glove/ring, etc), or are very expensive to run.
Visit http://brilliant.org/Murtaza/ to get started learning STEM for free, and the first 200 people will get 20% off their annual premium subscription.
In this video, we will learn how to track hands in a 3D Environment. We will write the Hand tracking code using python OpenCV and CVZone. From there we will transfer the data to our unity 3D Env...
@golden lichen didn't mention I guess
@mossy snow wait shit i just set the Y to 30 and it works??
I can try that, thanks
well i shouldnt because 30 is only for when going up a slope and -30 for when going down, but this is actual progress
i guess ill math.sign the projectonplane?? hol on
@mossy snow i might have just done it??
Do you know if it is possible to replace each character with the newer characters? Like if I had "Dog" and it replaced it with "Cat" but one character at a time.
for some reason I cannot use ParentConstraints in script. Do guys have an idea why that is?
Its like visual studio doesnt know what it is
thanks a lot. Thats it. wasnt aware of that.
can somone help me with this problem when I tried to load my game into a browser?
it is a multiplayer game
look at the browser js console like it says to see what the error was
Best guess would be that you're using something that isn't available on WebGL
well that wasn't helpful. Does it run normally in editor or as a standalone build? Do you have any dependency that doesn't work in webgl?
It usually runs as a standalone build and it runs normally within both the editor in the build. I am not aware of any dependency that doesnt work in webGL.
I have created a project with a different version of the game and it has run fine
does the universal render pipeline work within WebGL?
the docs say yes
hm\
should I provide links to my scripts such as the playerManager, Launcher and playercontroller?
you should look more closely at the logic which executes after you press the start game button
how do I view the logic?
got it
I fixed the problem. I found out that one of the scripts had UI elements that were public variables, so I simply changed them to serialized fields
thanks for everyone who attempted to help
what
Is there a way to do foreach key in _myDictionary or no? Foreach keyvaluepair doesn't let me modify the value.
And I don't see how to do a for loop
foreach (var key in myDict.Keys)```
whats the defaultvalue of a float playerpref?
and i see now i spelled score wrong lol
what is causing it?
- GetFloat has an overload that allows you to specify your own default value that is returned by it so you don't need to use an if statement for that if you were just going to assign some other value
- the default value of a float is 0
this is a code channel
thanks
ok I see
is it possible to somehow make an ordered dictionary / hashmap? I want both mapping and iterating
hey,
is there is any way to curve the corner of an image within unity ?
is it possible to curve only 1-2 corners out of the 4 corners?
No
The image is sprite based, you can't modify it. There are assets on the store they let you generate UI images to do exactly what you're asking.
I'll take a look , thank you
Does anybody have any advice for nested coroutines for resetting cooldowns? I would like to make my character have a cooldown reset if he collects a powerup while currently experiencing the same powerup. Say they pick up a speed up, and it lasts for 5 seconds. If they pick up another speed up during that 5 seconds, I want it to reset to 5 seconds again. Anybody know the best way to do this?
You can save the reference to the coroutine and check if it's still running
if it is, stop the coroutine and start anew
hi guys, whenever i exit play mode i get this error:
The property database "Library/Search/propertyDatabase.db" is already opened.
UnityEditor.EditorApplication:Internal_InvokeTickEvents ()
ive googled but not sure how to fix it, think it might be related to a crash im having
just set the cooldown to 0 at that point
check if the coroutine is still running and if it is set the cooldown to 0
no need to stop the coroutine and rerun it
unit is null
The same as the default value for a float . . .
Wouldn't thatt make it false..?
What does "=>" do? I've tried searching for it, but I can only find examples of it being used - not explanations of it.
it's used for defining lambdas and expression-bodied members
it separates the parameter list from the body of the function
good practice is to try using => as much as possible
watch VS suggestions closely as it usually instructs on how to do so
Does it have a name?
Lambda operator @lunar forum
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator
we call it => ๐
Is there a way to place battle music when an enemy is nearby or is in range?
Most definitely.
Triggers, distances, raycasts, manual custom intensity etc.
Yeah but how do you turn the main music off once you get close to an enemy.
In our first horror game, all the audio is proceedural. We track how afraid we think the player is, and select visual and audio effects based on their anxiety, fear, and anger levels. So a heartbeat starts up, gets louder. Interacting increases possibility of audio playing audio clips etc. And fear spikes (seeing an alien) is what triggers big scare samples
You can check the distance to the nearest bad things, how far they are, their individual power, when you last saw one. So just tie the audio in that way.
A simpler approach is just to overlap trigger spheres when near a bad guy
Or just trigger new audio if you become visible or detected (metal gear style)
And when you defeat it the main music goes back?
It's up to however you want to code it
Usually games do a fade on music transitions instead of* instantly/abruptly playing the next track
Yeah. In our case, anxiety slow reduces if you haven't seen anything scary in a while. Some things, like a flickering broken tv, still adds hidden fear. So it's environmental. But you can control all of that depending on the project
Just gotta code it ๐
So just basically just look up tutorials how to do music properly?
And give it a test?
Also how do you make Lego like damage. To where once they die pieces scatter and disappear for a few seconds and Lego builds?
normally its extremely hard to do procedual generating of those effects
ppl normally will break the model to pieces , and align them to make them look like a whole
when u need it to scatter, just scatter them
I mean like detaching them from the body.
for example, u have a kyubey doll, if i want myself to scatter when explode
i will make a complete, perfect kyubey model and a broken kyubey model
when kyubey "died", instantiate object with the broken model prefab , and apply forces to scatter it
modelpart.transform.parent = null;```?
Like do I just make the part of that body invisible. But wouldn't that make a more lag with the rig being on the floor everywhere?
Oh wait nvm.
Yeah I'm a newbie to this.
i am experiencing extreme lag spikes when generate perlin noise values my noise map is around 400 by 400 ish and i think unity is rendering the entire map at once, what steps should i use to optimise this make a chunk wise rendering or render area up to players visibility or the area of the camera is only rendered at a time? kind of new any ideas
first step for any performance issue is to use the profiler and pinpoint exactly what the issue is
Unity already performs Frustum culling by default so the "only render the area of the camera" thing happens automatically
We also have no clue how you "generate perlin noise". It could mean so many things, especially if there's some other meaning behind it, which is very much possible judging by how you're asking about rendering.
I generate 2 things an island ilusing cellular automata then I apply a perlin noise on of the island shape and generate biomes using the noise value of the perlin noise, that's pretty much it
When I generate a randomly using left click it gives me a huge lag spike for 3secs
That still doesn't tell us much. You'll need to share the relevant code. Or even better, do the profiling first and share the profiling results.
I think they are asking you "how" are you generating perlin noise
The thing is currently my map size is not exactly what I want I want the map to be alot bigger and I don't know how I could optimize the lag issue
Start from understanding what causes the issue first. Then you can think of solutions.
Ok wilait I'm sharing, and perlin noise is generated using the perlin noise function built in
is this after importing a model
hey so i have uploaded my code here https://paste.myst.rs/v2d262sh
a powerful website for storing and sharing text and code snippets. completely free and open source.
the thing is that i currently generate a map of the size of 100 x 100 tiles
and this small ends up give a bit of lag
and my plans are to have a world the sze 800 x 800 tiles
and when i do try to generate a world of that size it takes like a solid 30 seconds to just generate
and ends up being too laggy to even move around the player character
this is my inspector window
Does Unity provide any way to prevent a Rigidbody from colliding with a specific layer by instance?
There are layer overrides on rigidbodies, yes
Layer overrides?
Am I missing something lol
Only on the newest Unity verisions - 2022+ I believe
Generating the map would of course take a lot of time,especially if you do it on the CPU in single thread and without any optimizations. But there shouldn't be any lag after generating it normally.
Use the profiler to discover why it lags after generating the map.
Then no, you have to use the layer the gameobject is on
sorry kinda new to unity how do i use profiler
Google. It's not something we can explain in a few messages.
How would I use it by instance?
Just change the layer? What are you asking?
@chilly beacon the initial lag is caused by the for loops which is "okay" since you do sort of have to have a loading time in a game, it's expected.
I don't know why it lags during runtime though, it should only lag when you press the mouse button, or in other words, when you generate the world.
Yeah, I'm gonna change the layer, how does it prevent them from colliding with other layers?
Lemme do the funny, never looked at the collision matrix
sorry y bad it doesnt lag during lag time but couldnt the generating time be lowered
not really
I guess you could try using some optimizing tehniques, but I don't know any for loops
ok
If you want to optimize the generation, you'd need to either make it multithreaded using unity jobs system or GPU based using compute shader.
You could also profile your current implementation and try to optimize the bottlenecks, but there's a limit to how fast you can get it with one CPU thread.
Well, no, that's not the actual solution.
Based on the script instance, the collision should be set up
Let's say Layer1 is gonna instantiate a Layer3, Layer1 shouldn't be hit by Layer3, whereas Layer2 should be hit instead.
Same goes for Layer2 instantiating a Layer3 and doing the funny with Layer1.
Sounds like you just want a player's bullets to not hit themselves or something?
Something like that
Just use https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html between the projectiles and the object that created them
Yeah but that requires two colliders
alright so the things i need to look ater is either generate though multithread, or gpu based compute or use profiler to improve current gene. Got it thanks imma look into them ๐
Shouldn't Rigidbody have a collider?
If you don't have colliders then no collisions would happen period
so you don't have a problem
I'd suggest to use the profiler regardless, to understand why exactly your current solution is slow.
its because of the loops
not alot will be gained by profiling
Loops alone don't take time. It's what they're doing in the loops that is the issue.
By profiling they can see how many iterations of what calls take what time.
they can't really make it much more efficient, the loops are the problem because if you look at the code (no need for profiler) you can see that they have 6 different double nested loops, all that have 10000 calls
It could be even something unexpected, like massive GC allocations
which adds up to 60000 calls a frame
so yea, you can optimize the inside as much as you want, but the inefficient writing is the problem
Again, it depends on what calls they are. A CPU would crack 60000 additions in less than a millisecond probably for example.
if you look at the code you can see that they can't really optimize the inside of the loops too much because they are already doing what they need to do
you could gain maybe a few fractions of a millisecond, but that improvement still gets overshadowed by the fact that there are 6 different loops that all do different things (meaning you would need to optimize each loop). even if they shaved away a few fractions of a ms, the overall time taken will still be (6 x 100 x 100)
my bad
but arguing about this doesn't matter, since just tidying up the code will speed it up
I'm not saying that in this current situation, they can optimize a lot the inside of the loops.
But profiling would make it easier for them to see what the issue is. It is fine if you can figure it out just from reading the code, but it's not always possible. They should learn how to use the profiler even if in this particular case, it's already clear what the issue is.
Or are you gonna review personally every single script they share and tell them what the issue is? Teach them how to fish, don't give them the fish.
I'm not saying that, I'm saying that the profiling in this case is useless because the reason is beyond obvious
digging with the profiler while not understanding the fundemental problem of using too many loops for using necessary complex tasks will only send you in a rabbit hole of insanity because you'll be shaving off insignificant amounts while ignoring the very simple problem
@chilly beacon https://paste.myst.rs/htvllatc
try this
a powerful website for storing and sharing text and code snippets. completely free and open source.
profiling is great if you eliminated everything else
The profiler would clearly reveal that the issue is with the number of calls from which you can understand that the number of loops is the issue.
also I missed a loop
it was actually 300000 calls
with the code I sent it should be only 50000
true
is there way to add mod support to your game
did you google it
The thing is I don't know when to for loop to avoid such discrepancies
Apart from "Google it", how exactly do you expect us to answer this? There is no specific way to add mod support.
I have two MonoBehaviour scripts, let's call them "Health" and "AICharacterController". I want the AICharacterController to listen for updates to a variable in Health. Is this possible, and if so, how?
events. or just get a reference and poll the value in Update
how to get a reference: https://www.youtube.com/watch?v=Ba7ybBDhrY4
Events is what I am looking for. How do they work?
I am trying to learn new things after I realized that I am kind of stuck in my ways
This video explains how to use special delegates called Events in order to subscribe methods (functions) to create flexible broadcast systems in your code!
Learn more: https://on.unity.com/3iVYXhx
HI everybody, I'm trying to split my dynamic textures load so that my game freezes less but I'm a bit confused about how to proceed. From what I understand, there seem to be two ways to handle this, load asynchronously or using multithreads. Is that correct? Let's say I need to load 10 textures of 4Mo on average, if I use File.Load, then the game would load them one by one and hang until all of them are loaded right? If I load them asynchronously, will it avoid this freeze?
Thank you ๐
assetbundle / addressables, load async ?
im trying to use layermasks in code, where all layers are affected except Ignore Raycast layer.
do I input in c# the binary representation of 111011, 110111, or their decimal equivalents?
*i know ignore raycast layer is automatically ignored, but assuming i want to do it thru code
you need bitcasting afaik, or you just use a pbulic layerMask property
bitshift, not cast ๐
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
is bitshifting the only way? seems like a hassle to mix a collection of ands and ors ๐ญ
just use a LayerMask variable
I have tried using public layerMasks and they work fine, but it makes the organization messy
Did you read the link? You can just tell the layer int and bitshift it to a layermask to use it
yes, I've read about bitshifting, but the issue is requiring multiple 1's not in sequence
so youd need a colletion of and and ors
or just use a LayerMask variable and the ever so convenient LayerMask.GetMask method
Ah my bad, forgot to mention. My texture are in the StreamingAssets folder, not in a bundle or adressable
mulitple 1s? You mean a list of layermasks?
looks promising!!
Yeah, don't use literals for the masks because once you change them on the inspector then you've got to change them all in your code.
oh yeah ok good idea
the message I tagged you in has a pastebin link, the code there is fixed, read the code and you'll see
probably best to use UnityWebRequest to load your textures async
yes and im getting information from 2021
did something happen in the last two years that made information from 2021 no longer valid?
Yes, that's why I changed too. But when my character textures are loading, I still get a freeze.
I'm using a coroutine to load the texture using UnityWebRequest
`
UnityWebRequest uwr = UnityWebRequestTexture.GetTexture("file://" + path);
yield return uwr.SendWebRequest();
if (uwr.result != UnityWebRequest.Result.Success)
{
//Error
}
else
{
// Get downloaded asset bundle
Texture2D tex = DownloadHandlerTexture.GetContent(uwr);
}`
This is my coroutine, from what I found online. Textures do load but still some freeze. I was expecting something a bit smoother, like the character still playing the animation and the texture filling little by little like some games do
Loading a texture from disk will always cause a main thread freeze, duration depends on its size.
So what's the point of loading async?
The actual loading is async, the object init is not
Hm, so if I want to make it faster I'd need to add some multithreading ?
Is it possible?
Ah I see
Best you can do is load images as structured byte arrays (DDS) and write those directly into a preallocated texture
Ok, just one last question then, what takes more time, the texture loading or the texture init ?
Depends on how big the image is, itโs format and where you load it from. Typically though, the decompression (jpg/png) takes the longest (assuming SSD on the local PC)
Ok, and the decompression happens only once during loading then?
it happens whenever you load/save an image to disk as jpg/png unless you cache the compressed byte array
Got it, thanks!
hey guys
Hello guys, I am wondering if someone can help me with a question about null handling. Is a simple null check with an if statement the standard in Unity or using C# try and catch (error handling system) a better practice?
avoiding null would be best practice, but if you cant avoid it for some reason, having a simple null check is totally fine
NullChecks seem to be better for scenarios where you want to have an individual reaction to each possibility. E.g.:
if (renderer == null)
renderer = GetComponent <Renderer>();
if (collider == null)
collider = GetComponent <Collider>();
if (stats == null)
Debug.LogWarning ("Stats variable is not set up in GameObject: " + name, gameObject);
TryCatch seems to be better if you want to cover a bigger area of code with a single reaction. Also, TryCatch is pretty neat if you're using methods you don't want to modify.
@hard estuary so for simple object collisions a try-catch will be a little overkill I guess
So for simple code this:
Player player = other.GetComponent<Player>(); if (player != null) { player.damage(); }
Is better than this:
try { player.damage(); } catch (NullReferenceException err) { Debug.Log("Object other is Null"); Debug.Log("System Message: " + err); }
Thank you both
Do not try-catch expected behavior in your code ever. You are always able to check beforehand if certain conditions are met, and bail out of execution if predicates meet. Try-catching exists to handle unexpected exceptions in your code that do not happen under normal circumstances , and the point is properly informing users and handling the code in an alternative way if it can be saved. Throwing exceptions is also costly on performance.
If you get a null error, you SHOULD get it to know your code is not optimised very well. Guessing that you might have an object or not is a bad habit of avoiding errors ๐
Hi there. Does anyone know how I can set the default parameter for a Vector2 to zero when passing it via function parameters? I've tried the following but I get an error.
public void init(Vector2 pos = Vector2.zero) { }
By default it is 0.
Value types are initialized using default values, and integers are 0 by default ๐
Follow the recommendation listed there: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing
Google "reference" types and "value" types. It's very useful to understand the differences. Reference types are null by default and value types can't be null @faint horizon
@thin aurora So if I want to pass nothing via the parameters would this still work?
Make your method declaration public void init(Vector2 pos = default) { } and you won't be required to pass the pos parameter.
You also owe me 10 seconds
https://docs.unity3d.com/ScriptReference/Animator.GetCurrentAnimatorStateInfo.html