#archived-code-general
1 messages · Page 142 of 1
List<int> nums = new() { 1, 2, 3, 4, 5 };
List<int> result = nums.Where(x => x < 3).Select(x => x * 2).ToList();
x => x < 3 is an anonymous function that returns true if its argument is less than 3
The fuck?
x => x * 2 is an anonymous function that returns its argument times 2
This filters the list to numbers less than 3, then produces a new list whose values are doubled
What would take me an entire function in and of itself to do, bro does in 2 lines
result contains 2 and 4
You could have make the functions non-anonymous, of course
public static bool LessThanThree(int x) {
return x < 3;
}
obviously that's a bit of a nuisance
this must be how newton felt when apple fell on head
You would then do nums.Where(SomeClass.LessThanThree) instead of nums.Where(x => x < 3)
Either way, you're saying "hey, use this function!"
This is ultra-common in functional programming.
and functional programming looks sort of like this: just transforming data, one way after another
what I mean more is,
if given this problem
i’d have to do each operation separately
players
.Where(x => x.health > 0)
.Where(x => x.faction == Faction.Dudes)
.Where(x => x.florps == 10)
operation after operation
ok what the fuck does this even do lmao
well, read each line
line 2: .Where(x => x.health > 0)
what do you think that produces?
is this even correct syntax
yes, i've just split it across a few lines to make it less cluttered
oh i see
you can reason about each line completely separately
what does => do
when you define a method like this, you're saying "this class has a method called LessThanThree"
you access it as SomeClass.LessThanThree
x => x < 3 creates a function, but it's not named anything
it's just an object.
you can stuff it in a variable, of course
var lessThanThree = x => x < 3;
aka
System.Func<int, bool> lessThanThree = x => x < 3;
a function that takes an int and returns a bool
If you need to perform several statements, you add braces
System.Func<int, bool> lessThanThree = x => { Debug.Log("x is " + x); return x < 3; };
which is equivalent to
public static bool LessThanThree(int x) {
Debug.Log("x is " + x);
return x < 3;
}
Anonymous functions let you construct the function exactly when you need it. They can use local variables from the context they were created in.
Player admin = GetGameAdmin();
var nonAdmins = players.Where(x => x != admin);
christ i feel like a fucking idiot right now
i think this makes sense but i’d probably need to actually practice it
(not sure how to do that since i don’t really get it that well)
No need to run before you can walk. Anonymous methods are not required to understand delegates. They're useful for when you do understand delegates.
Indeed.
public static bool IsCool(Player player) {
return player.name == "chemicalcrux";
}
public void Start() {
foreach (var cool in players.Where(IsCool)) {
Debug.Log(cool.name + " is cool");
}
}
using names makes linq especially fluent looking
players.Where(IsOnFire)
me googling what Linq is
It provides a bunch of methods for working with lists
(and any other thing that looks a bit like a list)
what is .Where
well, before looking it up
can you guess what a function called "Where" does?
a function that takes a list
and returns a new list
evidently not, no
"give me a new list where the items match this rule"
yeah ngl would not have guessed that
i do think "Filter" would be better
i would have presumed it returned where anything that met that condition was in the list
LINQ uses a lot of terminology from databases
bingo
oh
well, not the indices :p
yeah
i misread.
you’re chemicalcrux not misread
Except is a nice one
List<int> numbers = new() { 1, 2, 3, 4, 5 };
List<int> evens = new() { 2, 4, 6, 8, 10 };
List<int> result = numbers.Except(evens).ToList();
what do you suppose the result will be?
so you’re making a new list on the fly with .Where and incrementing through that, logging anyone who is cool
and doing so in such a short space
Got Dam
iterating through that, not incrementing, but yes
sorry iterating
It results in very terse code
I think it's also the most obvious way to demonstrate how to use delegates
The other straightforward example are events
where you say "hey, call this method when something happens"
is there anywhere i can practice using delegates?
best way to handle knockback is to add an impulse to the target in the forward direction of the player when i am hitting?
well, in the direction of the blow
which might just be the forward direction of the player
ye what i said
but when i tested it feels like a force push from star wars
even when adding momentum and such
then the enemy doesn't have much drag
You'll use them in a few contexts in Unity
For example, if you use the new input system, you'll use them a lot
InputActionReference jumpAction;
void OnEnable() {
jumpAction.action.performed += Jump;
}
void OnDisable() {
jumpAction.action.performed -= Jump;
}
performed is an event. You can subscribe to it by adding your method to it. You can unsubscribe by removing the method.
your Jump method gets called whenever the player hits the jump button
sorry again if wrong channel, but the hell is this now?
ill try running unity as administrator
well, it says your scripts had compiler errors
i am 100% sure the error isnt in my code, it also goes to playmode successfully
Is there no stacktrace?
Does the error persist after you clear your console and trying to do something?
dont know right now
im trying to open it back
because every time i close it, it hangs in task manager, if i kill it it says "cant kill an exiting process" or "access denied" and also "project is already open"
smells like a "delete library and let it reimport" situation
its currently at this "c library stage" and it errors mostly here, lets see
anyone knows what its now?
public class P_Input : MonoBehaviour
{
Vector3 moveInput;
Vector3 rotateInput;
public float rotationAxisX;
public float rotationAxisZ;
public float xAxis, zAxis;
private void OnEnable()
{
InputSystem.EnableDevice(Gamepad.current);
}
private void OnDisable()
{
InputSystem.DisableDevice(Gamepad.current);
}
private void Update()
{
HandleInput();
RotateInput();
}
void HandleInput()
{
xAxis = moveInput.x;
zAxis = moveInput.z;
}
void RotateInput()
{
rotationAxisX = rotateInput.x;
rotationAxisZ = rotateInput.z;
}
private void OnMove(InputValue value) => moveInput = value.Get<Vector3>();
private void OnRotate(InputValue value) => rotateInput = value.Get<Vector3>();
}```
Hi sorry, my rotation works thru right analog stick. But the thing is, it works only if i push the stick from left to right vice versa and diagonaly too but it wont rotate if i push directly up or down. It need it to do that so i can make my character rotate kinda smoothly based on where i push my stick?
switch z to y
Sorry no, it works weird. because my game is like topdown, when i switch to y, it doesnt rotate like how it should. it rotates by flipping around.
well, still, there's no inputVector.z afaik
also, when do you call OnMove and OnRotate? I don't see that in the code
and on top of that, are you sure you handle rotation correctly? I can't tell from this code either
but for starters I think your stick doesn't work at all on the Y (vertical) axis because you're not using it
@wide fiber This should be enough to handle the input:
public class P_Input : MonoBehaviour
{
public Vector3 moveInput;
public Vector3 rotateInput;
private void OnEnable() => InputSystem.EnableDevice(Gamepad.current);
private void OnDisable() => InputSystem.DisableDevice(Gamepad.current);
private void OnMove(InputValue value) { var input = value.Get<Vector3>(); moveInput = new Vector3(input.x, 0, input.y); }
private void OnRotate(InputValue value) { var input = value.Get<Vector3>(); rotateInput = new Vector3(input.x, 0, input.y); }
}
or if you have your extensions set up:
private void OnMove(InputValue value) => moveInput = value.Get<Vector2>().XZ();
private void OnRotate(InputValue value) => rotateInput = value.Get<Vector2>().XZ();
ok i will try that. thank you so much!!
np!
how to make breakpoint work on line 112 just when it throws error?
is it even possible?
Does someone know why this doesn`t work? Doesnt give an error, does nothing.
using UnityEngine;
public class Movement : MonoBehaviour
{
private CharacterController controller;
public float standingSpeed = 20f;
Vector3 velocity;
public float gravity = -10f;
public float jumpHeight = 4f;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
// Set speed based on the character's state
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 direction = transform.right * x + transform.forward * z;
controller.Move(direction * standingSpeed * Time.deltaTime);
// Gravity and jumping code...
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (velocity.y < 0 && controller.isGrounded)
{
velocity.y = -2f;
}
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
}
hello, I am trying to figure out how why this internal Unity process is taking so much time to execute, and I am hoping someone can point me to where to look:
the DeformationManager.LateUpdate function is taking at least 100ms per frame in the profiler. anyone can help me understand why and how to improve it? thanks
Are you using the 2D Animation package?
yes I am. and it's in Unity 2023.1.1f1
Can you see what version you have of the package?
10.0.2
an aside note, I disabled all my monsters in the scene that use the IK skeletons, and it improved the FPS drastically. the game is running a Server/Client using Mirror
How many do you have?
a couple hundred
Ok, then I think that amount of time is expected.
You could try using the GPU skinning option if you're using URP.
ok I am using URP but haven't heard of that
I don't know where it's configured, I just know it's available in version 10+
okay thanks. i don't think a couple hundred monsters is many for a Server to manage across multiple scenes in my MMORPG, so I'll have to think more about how to optimize this
I doubt the server needs to update mesh skinning. You should look into disabling the system on the server.
And the client would only update ones visible to it.
For my teleporting script, I made it so when the player is pressing E AND touching a door tagged "SafeZoneDoor" they get teleported to an empty tagged "SafeZoneCenterEmpty", or at least that's what is supposed to happen. for reasons I do not understand it gets teleported across the map instead.
https://paste.ofcode.org/EMXLQ2ZZ5de5iQ2s48dhZH
The player should be getting teleported to the transform.position of the empty gameobject
yeah that makes sense. when i'm playing as host, i'll need to have it enabled probably. but need to figure out how to only update ones visible to it. should be handled by my Spatial Hashing Interest Management
also, the game runs perfectly fine outside of the editor as separate Client and Server, this is only in Host mode that i experience all this latency and it's tough to test.
Hi, i have a question about DOTween. When i use DoFade(0f, 1f) on an image it works fine, the image fades away completely. But when i use i.e. DoFade(100f, 1f) it does nothing, but it should be reduced by about a third, right? Alpha is between 0 and 255.
*reduced by about 2/3
I expect DOFade uses the 0-1 range instead of 0-255.
Didn't think of that, i'll try it quickly and report back.
In my 3d game of couch party type, I have 2 characters, one of which is wasd and the other is guided by an arrow. I want to tie these two characters together with the help of a chain or rope and just want them to go around together. Is there a resource or method that can help me do this?
You were right, works like a charm 😄 thanks!
Does someone know why this doesn`t work? Doesnt give an error, does nothing.
using UnityEngine;
public class Movement : MonoBehaviour
{
private CharacterController controller;
public float standingSpeed = 20f;
Vector3 velocity;
public float gravity = -10f;
public float jumpHeight = 4f;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
// Set speed based on the character's state
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 direction = transform.right * x + transform.forward * z;
controller.Move(direction * standingSpeed * Time.deltaTime);
// Gravity and jumping code...
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if (velocity.y < 0 && controller.isGrounded)
{
velocity.y = -2f;
}
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
}```
a late thank you for taking the time to explain all this
<3
Depending on what "it doesnt work" means, I assume you mean it doesnt move when you give it horizonal/vertical input, and I assume the script is attached to a relevant object with all your values assigned correctly, I would start with debugging it - comment out all your gravity/jump logic, output what your "x" and "z" values and "direction" is, and maybe output the math your using inside Move, to make sure your getting the values your expecting, if it moves then, likely your gravity logic is affecting it, if it doesnt, likely your calculations may be wrong
I am currently working on a gun script for a top down shooter game, but when in AR mode it instantiates too many bullets at once and I can't seem to figure out what is going wrong in the script.
you probably use GetKey
but I cannot say more without further context
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
what is that?
How am I supposed to put the text in the discord chat
I am trying the links now
but it is not a long script
yeah, I am looking on it already
alright thanks
I think you do really have some troubles with brackets
What do you mean?
your brackets are placed badly
also you should not compare bools
bool isPistol = true;
if (isPistol) // works
if (isPistol == true) // works too
ok I will change it
please check what method spawns bullets
What
please check what method spawns bullets
The bullets are spawned in ShootMechanicAR()
oh, I haven't it before, you start this coroutine every update
but yeah, just when button is pressed
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
if (isPistol) ShootMechanicPistol();
else if (isAR) canShoot = true;
else if (isSniper) canShoot = false;
}
else if (Input.GetButtonUp("Fire1") && isAR == true) canShoot = false;
if (canShoot) StartCoroutine(ShootMechanicAR());
}
your script ordering is quite strange
but yeah, I think it's quite logic that canShoot is true quite often
just print when coroutine starts
ok I will try it out thanks
Ok so the shoot function is being called when the button is pressed but the same problem is occuring and it is that when the function is being called it spawns too many bullets at a time. I took the code block that you send and replaced my whole update function with it.
yeah, that's just a little bit more correct method
I have already that that canShoot is true too often
you already know your issue, try to solve it now
it shouldn't be that difficult
but wait, anyway.
it's just called when button is pressed
that shouldn't spawn to many bullets
I can show you a video of what is happening if you want
yeah
but what do you even do this?
yield return new WaitForSeconds(0.5f);
it's at the end of your method
Yeah I was just trying that out to delay it everytime the function was called
I probably just left it in by accident
I see, it won't work so when it's at the end
you probably gonna use yield return null; or yield break;
what a nice weapon though
Yeah I will use that one as a minigun weapon
But I am just trying to make a simple AR now
You unlock the guns using points you get from killing zombies
AR will be cheaper than minigun
they can just drag it here
@unique sparrow print what method is called
and ShootMechanicAR() should have void type too
like print it when it is called in the debug log?
'''void IEnumerator ShootMechanicAR()'''
no.
Everyone can't see the video and most ppl won't download a file from discord. It limits those who can help; just tryna help them get all eyes on it . . .
void ShootMechanicAR() { ... }
yeah, that makes sense, sorry
yes, print is the same like Debug.Log
yes, I haven't said that it gonna fix anything
So no IEnumerator and I just get rid of the coroutine entirely?
Keep in mind Print only works with scripts derived from MonoBehaviour. It won't work on regular classes or SOs. Debug.Log works for everything though . . .
yeah, print is 3 characters less to type
also they gonna see it when they get error
What's a good way to implement status effects in my game?
I have a character that runs around and shoots multiple projectile types, and I want each type of projectile to apply a unique status effect to the enemies it hits (slow, stun, bleed, etc) and I also want to include other status effects like immunity.
What's a good approach to do this?
no, you don't need it to be coroutine
it should be void, because you don't need to yield return anything
I just upgraded versions from 2021LTS to 2022LTS and am getting a bunch of warnings related to VFX Graphs and the generated compute shaders. Anyone know how to fix these? I tried resaving/recompiling the graphs but no dice.
I don't see any prints
Hey something to bother
I been trying to follow a guide on making attack combo animations
But from what i have done im having an issue where my statemanger isnt swapping states so i cant get the animations to play at all
Im not so sure why its not swapping so i was looking to maybe get some help
I see, how often is it printed?
835 times so I believe every frame
nice
So how would I go about slowing it down so it is called not every frame but maybe once per second
well faster than one second
no, it's called when you hold your button in update
here
else if (isAR) canShoot = true;
you should call that method here
else if (isAR) ShootMechanicAR();
that's because you assign canShoot to true when button is pressed
and assign it to false when it is released
bullets are spawned within time you still hold that button
it was really stupid of me not to mention it
no, it doesn't
I have already said you your issue
fix it
if you need it
you can slow down the instantiation by adding offset, but first fix this
so I move '''cs else if (isAR) canShoot = true;''' right above else if (isAR) ShootMechanicAR();?
you, you just remove it
don't use canShoot
just use that coroutine when you need it
and ping me, please
So I just removed else if (isAR) canShoot = true;
yes
and you remove canShoot permanently
And I do a coroutine instead?
oh, sorry, no. I meant different code haha, sent the wrong thing. I wanted to send this:
using UnityEngine;
public class OpenDoorATM : MonoBehaviour
{
public float interactionRange = 3f;
public KeyCode interactKey = KeyCode.E;
private bool isInRange = false;
private void Update()
{
if (isInRange && Input.GetKeyDown(interactKey))
{
PerformInteraction();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
isInRange = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
isInRange = false;
}
}
private void PerformInteraction()
{
Debug.Log("Interaction called!");
}
}
no, I have said you everything already
you call method instead
isn't it just better to do in OnTriggerStay ?
yes, it is
Hi! This might be a stupid question but I'm trying to figure out why my ScriptableObject state is persisted on Unity Editor but on Android it seems to reset on each application run. For example property amountAvailable is reduced to 0 during runtime and properly persisted on the editor but is reset back to 1 on Android on each run.
Any ideas what I might be missing here? Below is simplified item class in question:
[Serializable]
public class Item : ScriptableObject
{
public ItemType itemType;
public int amount = 1;
public string itemName;
public string description;
public int maxAmountAvailable = 1;
public int amountAvailable = 1;
}
Ok so once I have done that how do I offset the ShootMechanicAR?
have you already fixed your error?
I am tryint
trying to I am not completely sure what you mean
So I get rid of canShoot
That is the way ScriptableObjects work
I don't see any reason for you to do shooting delay if you haven't fixed your issue yet
and run a coroutine instead?
you need to use a fireRate (basically a cooldown) and shoot a bullet when that time has passed . . .
they haven't fixed their initial issue before
https://gdl.space/ocuxiyofud.cpp so this is what I changed it to but now the AR acts like a pistol
isn't their problem the constant instantiation (shooting) of bullets?
yeah, but your brackets are really..
Yeah that is my problem
they just have too many bullets spawned
they still need a fireRate to only spawn the bullet based on the rate of fire . . .
yeah
shootDelay or smth
that's what i was originally suggesting . . .
yeah, you were suggesting it before they have fixed their issue
they just need to do a coroutine
it's the best way that I see
but that is the solution to their issue . . .
no, that's not
So how do I put in the fire rate because it was working fine with the canShoot and all I needed was the firerate
private bool canShoot = true;
private IEnumerator Shoot()
{
canShoot = false;
// some stuff here
yield return new WaitForSeconds(2f); // do a variable from it
canShoot = true;
}
and then just check if canShoot
quite easy
hmmm, i wonder what that 2f is for?
exactly, that's the fireRate my dude . . .
the rate of fire at which the gun shoots . . .
oh yeah, that doesn't matter
my English is bad anyway
I dont understand how I am supposed to put this into my code. Do you want me to replace the ShootMechanicAR with the IEnumerator? And I thought I was supposed to get rid of canShoot?
you have understood the logic
yes, you got rid of it when we were trying to fix your previous issue
and you were not using it correctly
now you add it one more time
and yeah, now it's Coroutine
delay.
Can you put it in the code with the rest of the script so I can see where exactly I am supposed to put everything because I am still confused
I have written you that coroutine already
I don't see why can't you do it yourself
Because now it is saying on the editor that not all code paths return a value\
yes, because smth doesn't return a value
probably you return just in bracket or don't return at all
I still dont get it can you send what the update function should look like
In my 3d game of couch party type, I have 2 characters, one of which is wasd and the other is guided by an arrow. I want to tie these two characters together with the help of a chain or rope and just want them to go around together. Is there a resource or method that can help me do this?
I give up, you cannot even copypaste what I have sent you
Just call this Coroutine in Update, that isn't that hard, is it?
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
if (isAR && canShoot) StartCoroutine(ShootMechanicAR());
}
}
private IEnumerator ShootMechanicAR()
{
canShoot = false;
// some stuff here
yield return new WaitForSeconds(2f); // do a variable from it
canShoot = true;
}
I am trying to code a spline follower but I am spending hours and getting nowhere stumped. I know verbally exactly how I want it to work but I can't figure out where the problems that are @#$@^ing it up are occuring.
void Update()
{
if (animate)
{
UpdateTimeValues();
MoveTransformsOnSpline(spline, spacing, techTree, loop);
}
}
private void UpdateTimeValues()
{
for (int i = 0; i < techTree.Length; i++)
{
float velocity = (speedOverTime.Evaluate(techTree[i].time));
techTree[i].time += Time.deltaTime * speed * velocity;
}
}
public void MoveTransformsOnSpline(SplineContainer spline, float distance, SplineFollower[] followers, bool isLooping)
{
for (int i = 0; i < followers.Length; i++)
{
float t = followers[i].time; // Calculate position of each transform
// Check if t is out of bounds
if (t > 1 && isLooping)
{
t = 1 - t;
}
else if (t > 1 && !isLooping)
{
t = 1;
animate = false;
}
Vector3 position = spline.EvaluatePosition(t);
followers[i].transform.position = position;
followers[i].time = t;
}
}
}```
What SHOULD be happening is every array object moves along the spline at their own speeds and positions, but relative to eachother via their initial spacing
but what IS happening is it just completely @#$@6s up in new amazing ways every time I run it, sometimes they go backwards, sometimes they loop only once
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I didnt think it looked like too much code, thats not a large block to me it fits all in one screen
using System.Collections.Generic;
using UnityEngine;
public class MessagesManager : MonoBehaviour
{
}
[System.Serializable]
public struct TextMessage
{
public enum Senders { Dad, Wife, Son }
public string textMessage;
}
How do I have this enum be accessible from both the class and the struct?
place it in its own script . . .
Which?
Just a script dedicated to the enum?
the enum which you speak of . . .
an enum is like a class so just put the declaration at the end of your script
as long as it's outside of the class or struct its separate and not a child of that class or struct . . .
Hey again, when I set the constraint for the width, when I do preferred size, it chooses its own size
Unconstrained
Preferred size
Only adjust the one u want to stretch, the default setting is fine for width. I believe I choose the 2nd option in the dropdown to make it scale properly, although I forgot exactly what the options are
Width meaning horizontal
It does this
Acc it's working pretty well here
My thing is
I wanna increase the height of the sprite
from below only
I assume u probably want it on the green box itself, although this is more of a UI question now
It's in world space
It has a rect transform
When I try to use the rect tool it doesn't give me the options
i have a problem rn and it doesnt let itself fixed and i already changed to private and public again nothing works
ah, it's rect transform is... bugged out
Cuz it has a width of 1 and a height of 0
Oh I fixed it, I removed the rect transform
How can I modify this value? As in stretching it from below
Is there some sort of assembly seperation between classes under Assets\Scripts\Editor and Assets\SomeOtherFolder ? I can't seem to use any the namespaces in the editor folder in the other directories.
yes
correct, the Editor folder gets included in the Editor assembly. you should not be using the editor assembly in non-editor code either
Editor is a special folder. All scripts in ...what box said^
Phew, I was able to get around the issue by moving a class outside of Editor that is referenced by a scriptableObject
I've been trying to have a class picker in my scriptable objects
it finally works
2 days of work to avoid having to make and update a switch statement
i am using a Parallel Job to try and make noise for a sphere and it is coming back warped. i believe this is because of my x,y,z values and how i got them. i was just wonder if anyone knows the corect way to get these values or if I did code this rights the job is just messed up because it is a Parallel job. i had it as a normal job and was working fine just slower
var x = index % Diameter;
var y = (index / Diameter) % Diameter;
var z = index / (Diameter * Diameter);
I have this script that spawns textmessages and resizes them automatically, but if the box is too big it starts to overlap, I tried to fix it using this line of code but it didn't work
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
void SpawnTextMessages()
{
for(int i = 0; i < textMessages.Length; i++)
{
Vector2 spawnPos = new Vector2(messageYPosition.localPosition.x, messageYPosition.localPosition.y + spaceBetweenMessages * i);
GameObject spawnedTextMessage = Instantiate(messagePrefab, spawnPos, Quaternion.identity, messagesParent);
TextMeshProUGUI text = spawnedTextMessage.GetComponentInChildren<TextMeshProUGUI>();
text.text = textMessages[i].textMessage;
SpriteRenderer spriteRenderer = spawnedTextMessage.GetComponentInChildren<SpriteRenderer>();
spriteRenderer.color = GetColourFromEnum(textMessages[i].sender);
Transform spriteTransfrom = spriteRenderer.transform;
float preferredHeight = text.preferredHeight;
int numberOfLines = Mathf.RoundToInt(preferredHeight / preferredHeightInterval);
spriteTransfrom.localPosition = new Vector2(spriteTransfrom.localPosition.x, spriteTransfrom.localPosition.y + (positionToSizeYRatio.x * numberOfLines));
spriteTransfrom.localScale = new Vector2(spriteTransfrom.localScale.x, spriteTransfrom.localScale.y + (positionToSizeYRatio.y * numberOfLines));
float halfHeight = spriteRenderer.transform.localScale.y / 2f;
spawnedTextMessage.transform.localPosition = new Vector2(spawnedTextMessage.transform.position.x, spawnedTextMessage.transform.position.y - halfHeight);
}
}
how to set cursor to the center of screen(i have lockmode locked)?
I dont come from C#, using async a lot recently. I came into a lot of places where I have a private async Task<T> MethodA() that contains a call to private void MethodB() and I dont really need MethodB to be async but I need to call it from the async method because thats just how the chain of calls came down to be.
Am i doing it wrong or is that okay? Mostly asking due to the annoying warning CS1998, last option would be to supress it project wide unless I can solve it without suppresion.
private async Task<T> MethodA()
{
await SomeTask; //etc
MethodB() //no await, synchronous method call.
}
private void MethodB(){...}
If you don't plan on awaiting anything in the method, then you can remove the async modifier, and just return a completed Task directly with return Task.FromResult(yourValueToReturn)
Is that a good practise (not that im doubting the answer) just wondering if its faster to return as is, or return a task? I guess creating a task creates some overhead.
But i imagine it is nothing.
Only return a Task if the caller is meant to be async and await it itself. Else the whole method chain can be non-async
What async does in reality is transform your method into a big state machine, that allows the code that's awaiting it to follow the progress of the task (running, completed, faulted). That's why you technically don't need any return on an async method that returns Task, it's all handled by the compiler for you.
With synchronous methods that still return Task or Task<T>, no state machine! You have to return a task yourself, and that's what Task.CompletedTask or Task.FromResult() does, gives you a task that's already completed
Ah thanks, I somewhat knew about the state machine but not the second part. Thanks, ill give it a shot. I usually dont want to suppress warnings unless really needed 😅
Hey, I am trying to make sprites flash white in certain situations, and currently I'm looking at doing it through a shader/material. The tutorial I found does this:
if I'm not mistaken, that creates a whole bunch of new materials, does it not?
Essentially every single object with this will get its own material?
assuming it was accessed with through the renderer then yea it will create an instance
But doing this sprite flashing thing seems so common
there has to be a common pattern for this, right? It's in every game basically
a common pattern for what?
does the tutorial u are following not work or something? im confused on what the issue is even
u can destroy them after they are finished being used, but u need to actually have them allocated somewhere so u arent just editing the actual material asset..
calling this overhead is like calling an int inside a class overhead
N..nah.. Every material is an entirely separate drawcall
https://docs.unity3d.com/ScriptReference/Renderer-material.html
i assume u are accessing the materials through here or renderer.materials. this is whats actually instantiating the material
It's one thing to have like, 10 materials or whatever rendering different things in the game. Another thing entirely to have 3-5 materials per enemy in the game
Materials are like, one of the easiest ways to mess up your performance, so I would think there was a reasonable way to avoid making more..
Unless you want to use a different set of sprites instead, i dont see what alternative you think there can be
Well, material property blocks are one right
not really
https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html
Note that this is not compatible with SRP Batcher. Using this in the Universal Render Pipeline (URP), High Definition Render Pipeline (HDRP) or a custom render pipeline based on the Scriptable Render Pipeline (SRP) will likely result in a drop in performance.
also
Use it in situations where you want to draw multiple objects with the same material, but slightly different properties
Right, so property blocks also break the batcher
Right, this would be what I want
like a variable "white" amount that I can set
Anyway, the difference is pretty extreme so ideally I'd want to avoid too many
I dont see how thats related to your case of wanting to edit a material at runtime
editing the material creates a new instance of it, right?
Which means every object that wants to edit its materials
has different materials
this is about the amount of materials on an object, not about editing them during runtime
Yeah and editing materials during runtime increases the amount of materials in the game
which is bad, because every material has a huge amount of overhead
enough that 4 materials lowered that guys fps from 50 to 14
have u noticed an actual performance issue yet or are just speculating
yea 4 materials... on a grid of houses...
Of course it depends on the amount that's used and how many objects are in the game right
Yes that applies to literally anything
profile, then worry about this if u notice an issue
It would just look like rendering takes a lot of time
It would also look you are thinking about this in your head and have not profiled
It's the same as getting the transform basically
you don't notice it until it creeps up on you
and when you profile, it just looks like you've reached the max your computer is capable of
I know optimizing early is bad, but if you riddle your game with really slow calls there's no saving it afterwards
each of them will show up as 0.02% on your profiler
theres a difference between writing clean code that you feel is sufficient for the task, and pre optimizing
no one out here intentionally writes slow code knowing theres a better solution, you only look if theres a better solution if you notice an issue
I mean that goes directly against my transform get example
we all do it without caching it
we know it's slow
you will never notice it being an issue
i honestly dont know what you mean with the transform example
who says thats what everyone does?
Most code I've seen does it
barely anyone actually stores references to game objects. U only need it if u need to use .SetActive
no, I don't mean another game object
if you want to get your own position, what do you do?
to the object you are in?
Im pretty sure its not slow as its cached
please dont tell me u are using gameObject.transform
you just write "transform.position" right?
As far as I see it, you would cache it yourself if you use it in update or whatever frequently, otherwise its not really a bother.
Sure, no need to cache it if you're just using it in start()
Still, it will never show up in the profiler, was my point
Getting "Cannot find action map 'actionMapName' in actions 'actionsName'" after renaming the action group (using new input system).
Pretty sure its a unity bug. How I can fix it?
if I wanted to have different functions for different types of weapons (first person shooter), should I A: have a functions that reads and ID and then executes code unique to that weapon type, B: Scripts for each weapon type called individually, C: IDK
How different are the weapons
If you have one weapon that shoots blue sparks and one that shoots yellow sparks, A.
If you have one weapon that shoots bullets and another that shoots turrets or frogs, B
shotgun, bolt action, full auto, and projectile
what is "projectile"
I think you can put that in one class
😊
why do all those switches when i can use a zero function and call it depending on the weapon type
Well, unity is not a huge fan of inheritance so y'know
you could have a component that hooks up to your shooting class
like a component with inheritance on it
i mean rn its just a script that hitscans from the camera with the rpm and damage referenced from a script holding the ammo, mag and weapon data
so it should be easy to add more
polymorphism thats the term
wdym? like a pannel that can be clicked to change stuff?
It disappears if I create empty oldActionMapName, but I don't want to have one.
An interface is basically a class you inherit from, just slightly different
basically it just promises a bunch of functionality
"I implement the gun interface so I promise you I have the "Shoot" and "Reload" functions."
the word "interface" really means like the section of the machine you interact with, and in code it means that you have this method of interacting with this object
Basically on a machine that has a "keyboard" interface, you know you can type.
On a class that has a "Fireable" interface, you know you can fire it like a gun.
functionally, quite similar to an abstract class
I am using auto-generated c# class from input system file. Saw similar problems on the forums, all without answers.
yeah thats just what im doing
its been 2 months since ive used classes and the first time in unity
You'd have to show the code
little rusty
As I mentioned, Unity isn't actually a huge fan of inheritance
it's more composition based
I really really fought against unity at first, really wanting to use inheritance, and I suffered for it.
You're better off just accepting composition and components
Fuck Around and Find Out
We are now enemies for life
terry davis dint die for this man
But, there are a lot of things that are very easy with composition but quite hard with inheritance
if your objects are clearly defined and have little overlap between them, inheritance is good. If your objects have random sets of functionality, composition is good
Like if some enemies fly, some enemies walk, some enemies have HP, some barrels have HP but can't walk, etc. Composition is fantastic
designed on concept good for random generation
not good at en mass random generation
There is no error in my code. Action maps look like this, I am using it like
_playerInput.GameInputs.Attack.started += HandleAttackInputStart;
No errors here.
I am getting "Cannot find action map 'Game' in actions 'PlayerInputBase (UnityEngine.InputSystem.InputActionAsset)'", second screenshot shows the place error from
idk i just hear instances of indie games struggling with random gen bc unity
What is NIS?
I thought unity was alright at random gen?
its just what ive heard
_playerInput.GameInputs.Dash.started += HandleDashInputStart;
_playerInput.GameInputs.Kaze.started += HandleKazeInputStart;
_playerInput.GameInputs.Kaze.canceled += HandleKazeInputEnd;
_playerInput.GameInputs.Attack.started += HandleAttackInputStart;
_playerInput.GameInputs.Attack.canceled += HandleAttackInputEnd;
_playerInput.GameInputs.CursorMove.performed += HandleCursorMove;
_playerInput.GameInputs.Movement.performed += HandleMovementInputPerformed;
_playerInput.GameInputs.Movement.canceled += HandleMovementInputEnd;
_playerInput.GameInputs.WeaponSwitch.started += HandleWeaponSwitchInputStart;
_playerInput.GameInputs.Reload.started += HandleReloadInputStart;
Oh, caves of qud is kind of
old
like, for 99% of all games created by humanity
random gen is fine with unity
for fucken, dwarf fortress, I dunno if it can handle it. Not really because the random gen more because of how big the world is
I don't see where you are setting the ID
"Cannot find action map 'Game'"
"GameInputs"
Pretty sure error not in my code. Want to find a way to somehow make unity forget about that old action map. I tried regenerate entire file, resave action maps, relaunch unity and all that.
don't those ID's need to match
How do i make a scene load when the player enters an area and unload the previous scene
_playerInput = new();
_playerInput.GameInputs.Enable();
Method param, yea
void HandleAttackInputStart(InputAction.CallbackContext context)
Sorry, again, I don't understand where you expect the action map "Game" to be
isn't your action map "GameInputs"
Yes, creation and enabling in awake, subscription in onEnable.
It worked fine with all this code before renaming. I renamed all my usage of it accordingly. Unity just doesn't want to correctly update info about it, I need a way to reset this somehow,
I am not expecting it, unity is.
I am using GameInputs as I declared in my action maps, but unity still throws error about "Game" action map about which I have no code at all.
Also, all inputs are working as expected.
Any idea how I can force it to save it? I tried to regenerate input class but no luck
so this is not your code, yeah? It's just where you are getting the bug
Yes, this is unity package code, PlayerInput class
I am following a tutorial, and theres this datatype the guy uses called "Action" what is it?
well, basically a function
I'm using 2021.3, maybe it changed
You can store functions and call them later
Ok, one other question
What does this syntax mean?
action?.Invoke();
I understand the Invoke(); part, but why the question mark?
it doesn't do it if it's null
You can use that for other things too
that ?. is the null conditional operator
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-
don't use it for types that derive from UnityEngine.Object through
exactly. it doesn't call the overloaded == operator that unity uses to check if something is destroyed
so since the underlying object is not actually null
it gets called, even though you probably expect it to be null at that point
like the object is destroyed
yep and you end up with a missing reference exception
Sometimes you want to use ? even for unity objects.
Alright. Never liked the ? operator anyway
it's rough to skim
myObject?.reference?.reference?.functioncall();
why would you? if you destroy something on the c++ side like using the Object.Destroy method it isn't immediately null on the C# side so it could potentially throw an error if you aren't checking for null using the == operator
Can you use it in the other way? Like the non-direct access way
target ? target.position : Vector3.zero;
that's a different operator, that's the ternary operator
in this case if target is a UnityEngine.Object it has an implicit cast to bool that does a null check so doing that is perfectly fine since that side of the operator expects a bool
both functionally and syntactically very similar though
myObject?. checks for truth in the reference, any reference other than null is "true", right?
no, that does not check a bool, it checks if the object is null. the ternary operator expects a bool on the left. it just so happens that unity gave UnityEngine.Object an implicit cast to bool
If you checking component from the same go and just want to check if it exists. If go will be destroyed, script that trying to get this component will be destroyed as well. So, I think, it's better to use ? in this case because it's much cheaper computationally.
I mean when you check for true/false, any value except 0 is true. It functionally does the same thing
and if it is destroyed then ?. will not see it as null whereas comparing to null with == will. your example is literally exactly why you would want to avoid the null conditional operator.
a ternary is not at all similar to a null propagating
checking if a ref is null or if a bool is true is the same operation, really
this isn't some crazy language where everything can be a bool implicitly
No. if it is destroyed then ?. will not see anything, because I specified that it is checking the same go.
wacky c++
https://docs.unity3d.com/2020.3/Documentation/ScriptReference/Object.html
This class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??).
insane python
idk why it went to the 2020 version on google, but u can change it to 2023.2 even, still the same-ish message
If go of the checked component will be destroyed, then go of the checking component will be destroyed as well because it is the same go. So in this case, there is no chanve to actully make this check. Or am I am missing something?
you can destroy a component without destroying the entire gameobject
if you know for sure that both objects will be destroyed at the same time, then sure you can use the null conditional operator. but if you decide to change things so that it isn't 100% guaranteed that the code using the null conditional operator will not run at all after the object is destroyed then you absolutely should use the == operator to check for null instead of the null conditional operator
Yeah, but if I am sure that it won't change then it's reasonable to use cheaper version.
"Cheaper"?
micro optimization at best, and one that isn't even worth the hassle of ensuring it won't break over just checking for null the way unity wants/expects you to
Is there a performance difference?
if your null checks are seriously causing any noticeable performance difference, you have bigger issues
Null check is null check
not sure if there truly is a performance difference, but if there is i imagine it's incredibly minor
Ah, apparently it doesn't matter.
this is like when someone said a reverse for loop was slower
"?." is basically compiled into a normal if check
It's just syntactic sugar
left here being the code, right being the "compiled"
as you can see, they are identical
right but this is in reference to using it for unityengine.objects which has an overloaded == operator that includes some casting. so ?. probably is faster, but not really but any measure that matters
Nanoseconds faster but also prone to being wrong under certain circumstances
Ah, so in theory if you really wanted to avoid the custom ==
But at the cost of being at the mercy of the C++ backend for whether or not you crash
Can't imagine why you'd want to bypass their custom equality check, but there might be some obscure reason
Never stop fighting against unity and their unity object tyranny. Force C# Objects, normal null checks, equality for all
Topple the hierarchy ✊
Thanks mao I actually think I know what i did wrong i didn't instruct the script to apply the new shared material to the rigid body
Hey, i am using a custom editor script and using OnSceneGUI, but it doesn't render every frame, i have to update something in the scene for it to be called, what alternatives do i have? I'm unable to look for information, whatever i find is obsolete or just doesn't work
I don't think that's possible. Unity only updates on certain events at editing time.🤔
i have found an answer: SceneView.RepaintAll();
Where would you call it though?
inside OnSceneGUI
or wherever you need to reload gizmos/editor visuals i guess 🤔
so in my case that would be pretty much every frame
Hi, I'm having a problem with the readiness of components on the Editor (works perfectly) vs Built exe... Is like in the .exe the components I rely on being ready are not ready and my game fails to initialize... is there any tip or guide on how to deal with this? Using v2020.3.27
Sounds like a script execution order issue
Just make sure you do self initialization in Awake and initialization that depends on other objects in Start
can anyone help me out? Ive been working on an android app that is pretty much all just UI, and i was just working on some scripts and now, for whatever reason, i cant click anything in-game
i think maybe it might be related to multiplayer but i literally have no idea what's causing the issue, what should i do?
kinda freaking out :,)
like everything was fine and then, next thing, im compiling the game for the 1000th time and now its like the game isn't even listening to any inputs
(not sure where to post this problem so ill post it here too)
if it's all UI and is suddenly not working then make sure that you didn't delete the EventSystem from the scene
oh my god its literally the most basic thing, of course
thank you :,)
i cant believe THATS what was causing all this panic im embarassed lmao
i just accidentally disabled it while testing apparently
Anybody familiar with the new multiplayer play mode feature? It just freezes on me in a fresh project, all players except the main editor dont show up and their consoles freeze, no error or anything, also nothing really going on in the project as its just out of the box a fresh project created 5 mins ago
Did you write any code?
No, just everything fresh, afterwards as a test i placed a cube that i rotate by script but that didnt change anything
Does your script have a while loop in it?
No
and i didnt use the script at first test either
using UnityEngine;
public class RotateBehaviour : MonoBehaviour
{
void Update()
{
transform.rotation *= Quaternion.Euler(360 * Time.deltaTime, 0, 0);
}
}
thats all it does
Yes
Sounds like it's not quite ready for prime time 😉
Yeah im aware, just wanted to test it and thought maybe anybody knows a quick solution
better than not trying
Hello I keep getting this message is there anyway I can fix it? It is a simple movement code and a easy fix but I am new to code and don't know what to do. Can someone Help me?
my code
configure your !IDE as you have already been instructed to.
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
You need to name your input actions the same as they do in the tutorial and remember to save
How do I download BoxFriend?
there's a channel for MPPM in the unity multiplayer server. the link is pinned in #archived-networking
read the guide the bot linked
I do not understand
it is a step-by-step guide that can even be localized to your preferred language if you do not understand english. follow the guide to configure visual studio
my language is not on there
then use a translator to follow the guide. having a configured IDE is a requirement to receive help here
well it's a good thing that the pictures are in the same language your visual studio install is in
traslated
What's a good way to implement status effects in my game?
I have a character that runs around and shoots multiple projectile types, and I want each type of projectile to apply a unique status effect to the enemies it hits (slow, stun, bleed, etc) and I also want to include other status effects like immunity.
What's a good approach to do this?
Any help with an index out of range exception?
void OpenSpace(Index index)
{
int limit = index.IsFromEnd ? (values.Length - 1) - index.Value : index.Value;
for (int i = 0; i < nextIndex - limit; i++)
{
values[^i] = values[^(i + 1)];
}
values[index] = default;
}
index.Value = 0, index.isFromEnd = false
limit = 0, nextIndex = 1, i = 0, values.Count = 6
I feel like there shouldn't be an out of range exception here.
array[^0] is the same as array[array.Length]
if you're gonna index from the end, start at 1
oh, that makes sense then.
Hey I'm trying to create a Scriptable Object and one of the variables I wanted to add was a Date, so that later I could organize all objects by that date! So far I haven't found a good way to store the date as a variable tho, is there a variable type for that?
dateTime.ToLong/ShortDateTimeString
DateTime.Parse()
serializes deserializes
i ve read again it seems you dont know of DateTime at all, study it
Thank you, I'll look into it!
What do you mean "later I could organize all objects by that date"? 🤔
Is that field for comment purpose like due date?
for context the player can pick up books and each book has a release date, I wanted the player to be able to sort the books by release date
Which part of this is the problem?
DateTime is nice for dealing with actual localized time, but if you just want fixed value something like int year, month, day could be sufficient
after researching DateTime a bit that does make sense, thank you!
There should be no extension (.prefab) for Resources.Load
There are multiple issues, that is only one of them
What are the other issues :(
ok, someone somewhere else said 'put it in the resources folder'. Well I changed Resources to a capital R, it didn't change anything
I never actually tried resources folder
Why the hell would you 😛
also for some reason using the fireball moves my player one space to the left 
Because it's colliding with the player... you should use layers to avoid that
The function looks very odd that it has to find player by name
Yeah... Find abuse!
To find the number of gameObjects with a tag, you'd use GameObject.FindGameObjectsWithTag(); but it returns an array, so I add .Length to it. But there's still a problem, if i store the length in a variable, lets say ObjCount, destroy a few objects with the tag, the value of ObjCount goes up, but doesnt come down. Are there any other methods / functions that give the number of GameObjects with a tag in unity?
What?
well this is the ontriggerenter on the fireball
I dont know how to explain it any better
Are you getting confused by the fact that Destroy doesn't actually happen until the end of the frame?
How else am I supposed to find the player in a static function
No, hold on
int is a value type, it will not update based on what happens in other code, the Length you get from the array has 0 relation to the Length property after it's read.
Lemme send screenshot
I meant this
Why would you make a static function for that
I dont understand
You should really just use your own list to track your objects rather than using stuff like FindObjectsWithTag
Why are you expecting the int to change after you assign it?
@deep oyster Don't let player projectiles hit player
Because its in Void Update
He may be trying to say the value will be higher than what it's supposed to be.
Show your code so we're not playing the guessing game
void Update()
{
SphereCount = GameObject.FindGameObjectsWithTag("Target").Length; //<-----This line
Debug.Log(SphereCount);
if(CanSpawn && SphereCount < MaxSphereCount)
{
MakeRandomSpawnPos();
Instantiate(Object, SpawnPos, Quaternion.identity);
CanSpawn = false;
Invoke(nameof(ResetDelay), Delay);
}
}
I'm no- oh. I forgot to change the Fireball item's tag to Projectile 
I have prefabs being created
You should use a registry of sorts... that call is too expensive
Why would you expect it to decrease if you're spawning objects
Because i destroy them after
Im making an AimLabs type thing
When they're Destroyed, you'll find fewer objects
Yes
But this is all very inefficient
What should i do instead
Use your own list
.
Find in Update isn't very nice
A whole array being allocated every frame too
Wouldnt it be better to have an int increment each time an object is created
Yes, that would be much better than the current approach
Why not
Because it is used by both Unity and C#
It clashes with System.Object and UnityEngine.Object
How do yall get that box around your text?
Like here
Also it gives no information about your variable
`code`
Surround your text with backtick
ahh
So would PrefabToSpawn be better?
What kind of prefab is it?
It's better, but being specific would be better-er
Theres more than one kind?
Be descriptive
I thought it was just prefab
the only reason that's not great is that prefabs tend to only ever be spawned, they have little use otherwise, so ToSpawn is communicating nothing
What kinds?
fireballPrefab for example
Ah
EnemyFish
or SpawnFireball(GameObject prefab)
This kind 🎯 ? Sure
Yes
Conventionally fields starts with lowercase but that's up to project
So how can i keep track of the number of GameObjects with a certain tag?
It's better to manage yourself, using List<GameObject> for example
its better to use components
@smoky ibex example of the tag you are interested in?
AimTarget?
Sure, if you have a specific script type use it
Yeah
Its hard to follow when 3 people are helping you at once 😅
class TrackedObject : MonoBehaviour
{
void OnEnable() => ObjectTracking.Register(this);
void OnDisable() => ObjectTracking.Unregister(this);
}
class ObjectTracking : MonoBehaviour
{
private Dictionary<Type, List<MonoBehaviour>> trackedObjects;
public void Register(MonoBehaviour mb)
{
if(!trackedObjects.TryGetValue(mb.GetType(), out var list)
{
trackedObjects[mb.GetType()] = list = new List<MonoBehaviour>();
}
list.Add(mb);
}
}
barebones example
to get count you simply
public int GetCount(Type type)
{
return trackedObjects[type].Count;
}
no tags, all automatic
failed with type
you should inherit that one
Is it supposed to be static? Hm
Uhhhhhhhhhhhhhhhhhhhhh
nevermind then
specify what you dont understand
The whole thing, but thats because im inexperienced lmao
ignore it then
So dont implement it?
i assumed you would understand this as an example of an approach
making it actually works requires a level that would click for you
so you can actually implement it from an example concept
otherwise you are in for a ride
in any case you know what is a singleton?
alright, do you have any "manager" object in the scene? where various "managers/systems" are?
that supposed to be present always
each as a single instance
I dont think so
so currently your game is assortments of components scattered and doing their own thing
Yep
hey uh
if i try and set a key on a dictionary that doesnt exist, will it create that key or will it return an error
through []?
like
dict[key] = value;
it will create it
What is a manager
see example above with ObjectTracking ?
there ObjectTracking acts as a "manager" its supposed to be present as a single instance, and manage a lot of other objects
Ahh
other names for it are "controller/system"
So you make a manager for keeping track of objects, then the gameobject creating the targets communicates with it to know how many to spawn?
What does that mean
class TrackedObject : MonoBehaviour
{
void OnEnable() => ObjectTracking.Register(this);
void OnDisable() => ObjectTracking.Unregister(this);
}
when this component is enabled, it will register itself
when disabled unregister
But what does registering do?
see code in the example
Thats what i dont understand
what precisely
The register method
i understand
im also explaining how to turn then unknown into known
break it down into parts, learn one part after another
eventually all becomes known
What is TryGetValue?
Btw you missing a ) in that line
ill cut myself some slack
Okay lol
SO
So, what about the line trackedObjects[mb.GetType()] = list = new List<MonoBehaviour>(); Why are there 2 = signs?
the TryGetValue(mb.GetType(), out var list)
has out keyword
this is a c# feature that allows to create a variable in place of its declaration, among other things
I understand that
I've seen it in Physics.Raycast
that line does exactly the same as
list = new List<MonoBehaviour>();
trackedObjects[mb.GetType()] = list;
since the assignements can be chained, given that operations return something
it is evaluated right to left
Okay, but how does this, in the end, tell me how many objects (that are somehow classed by name or tag) are in the scene?
public int GetCount(Type type)
{
return trackedObjects[type].Count;
}
What is Type?
well, its a vast topic but ok
most languages that have "classes"
are based on a thing called "type system"
I know what a datatype is
where a type is something that can be object
Like int, float, char?
so a class is a "type", a struct is a "type"
Type is a datatype that can hold a datatype 😉
Why???
Meta
to do stuff like .cache is explaining
so Type object stores all that type metadata
and is used to indentify types
well not stores all of it
its more of a handle
you can get all methods, properties etc through it
or like here you can use it to identify objects
C# allows something called "Reflection" which means basially the program can inspect itself. In order to do that you need to be able to represent a datatype in a variable. So you can say like "the type of this field is int" and express that in code
there are also datatypes for Methods, Fields, etc - all the pieces of the program.
Is this related to typeof()?
ie if you do print( collider.GetType().Name) it will print something like "UnityEngine.Physics.Collider"
yes
yes
Ahh
typeof resolves Type at compile time
Oh okay yeah
since every Type reference is unique per type, you can use it as keys in dictionaries
So, when i register something, Type becomes the type of what i registered?
Uhhh
im not sure if this is a coding thing but if i have bullets that stick to my character (or around my character) and they get stuck, how would i make the bullets phase through my player but not a wall
this ended up being much more complicated than i anticipated
what is the correct way to setup the indices of a quad (2 triangles)? If I'm reading my code correctly this should be what the indices look like (the paint sketch), but as you can see in the screenshot I instead seem to not have that, and also 1 of the tris is rendering the other way round for some reason.... What am I missing lol?
int VertexStart = i * 4; // if every tile takes up 4 vertices then we use i * 4 to get the correct starting vertex
int IndexStart = i * 6; // read above and replace some words, and you might understand my nonsense
UnsafeElementAt(Vertices, VertexStart).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(0.5f, 0.5f, 0); // top right
UnsafeElementAt(Vertices, VertexStart).UV = BlockInfo.UV + new float2(SpriteWidth, SpriteHeight);
UnsafeElementAt(Vertices, VertexStart + 1).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(-0.5f, -0.5f, 0); // bottom right
UnsafeElementAt(Vertices, VertexStart + 1).UV = BlockInfo.UV + new float2(SpriteWidth, 0);
UnsafeElementAt(Vertices, VertexStart + 2).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(-0.5f, 0.5f, 0); // top left
UnsafeElementAt(Vertices, VertexStart + 2).UV = BlockInfo.UV + new float2(0, SpriteHeight);
UnsafeElementAt(Vertices, VertexStart + 3).Pos = new float3(TrueWorldPos, BlockInfo.Depth) + new float3(0.5f, -0.5f, 0); // bottom left
UnsafeElementAt(Vertices, VertexStart + 3).UV = BlockInfo.UV;
uint UVertexStart = (uint)VertexStart;
Indices[IndexStart] = UVertexStart;
Indices[IndexStart + 1] = UVertexStart + 1;
Indices[IndexStart + 2] = UVertexStart + 2;
Indices[IndexStart + 3] = UVertexStart + 1;
Indices[IndexStart + 4] = UVertexStart + 3;
Indices[IndexStart + 5] = UVertexStart + 2;
its why i suggested to just ignore it
Alright, thanks either way
the winding order
you have arrows, just flip diagonal direction
I shall try that thanks!
i dont know precise winding order, but i always got around just by flipping until it works lol
if float3(0.5f, 0.5f, 0); // top right is top right why is
float3(-0.5f, -0.5f, 0); // bottom right bottom right?
wouldn't that be bottom left?
float3(0.5f, -0.5f, 0); would be bottom right
aha whoops, that would explain things thanks!
and vice versa for float3(0.5f, -0.5f, 0); // bottom left, but you probably see that now too
I have a script that writes this file to json, however "SerializeableTemperature" and "SerializableCondiment" gets included in the json file even if they're null. Is there any way I can only include them if a script initializes a new instance of them?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class SerializableObject
{
public bool instantiatedDuringRuntime;
public string id;
public int prefabId;
//Basic info
public Vector3 position;
public Quaternion rotation;
//Temperature
public SerializableTemperature temperature;
//Capacity
public SerializableCondiment condiment;
//Status
public bool status;
public SerializableObject()
{
instantiatedDuringRuntime = false;
id = "";
temperature = null;
position = new Vector3();
rotation = new Quaternion();
condiment = null;
status = false;
}
}
which json lib
Json.Net has a flag in its settings object
As they are already being "created" in your script, it makes sense, that it includes a reference to it even if its a null reference. And as cache asked, which json utility are you using?
on how to treat null, read docs
Double Strike 😄
thats per prop, there is global
No json lib, I just use Unity's build in.
Don't use that (default) one . . .
It's working fine for what I need it for.
weird that you came here asking questions then
And here we are telling you, that it does not deliver what you need it for right now 😄
Just switch to newtonsoft, its already in there in Unity latest versions I think.
So I need to rewrite my code entirely just to do this one thing?
You have one line that says, Convert or Deserialize or whatever.
rewrite entirely?
Rewrite that, same for other conversions
you mean rewrite 2 Serialize/Deserialize calls?
Its just the suggestion from this channel, use it or not. If you can live with a null object, which is fine too if you handle it correctly, stick to it. Just think a bit further that there might be more cases where you need some "advanced" functions
the issue is that you dont want to learn new library, but you require features that are not available in the one you know
solve the issue of not wanting to learn new library
start wanting to learn it
and its a smooth sailing
Sorry, I've never used a json library, don't know how it works.
It's not that I don't want to learn it, it would just be easier if I didn't have to since Unity's built in has been working perfectly for me up until this point.
But if there's no other way then I guess I'll have to look into it.
here are the benefits, some of them
unity one is a rudimentary, blackboxed lib with no customization
Its just one line of "using NewtonsoftJson" or something and then you just conver tyour JsonUtility.ToJson or how its called to the newtonsoft call, you find in the docs easily. Nothing more to do there and then you can use what you need from all the features
json.net you get full source, you get intermediary objects, you can add custom serialization routines for any type, you can customize it through api or source
you can do miracles with it
All right then, thanks.
And just think ahead. if you go into development, you might be fine with your solution in your personal project right now. But if you want to learn to work on other projects and within teams, you wont meet that builtin json again probably
bro.
Nullable<long>
show code
didnt know i had to do that
ty
you also have to check GetLong().HasValue
my guess its the purpose of being nullable there
as an indicator of whether or not the value was present
which is bad api, a bool TryGetLong(out long) would be better
Can anyone help me i keep getting a error saying The type name OnFootActions does not exist in type PlayerInput
Show some code, cause the error is already telling whats wrong
I guess this is more a #🖱️┃input-system issue. Can you post your stuiff there including your input asset inspector?
i did
you didnt
Hey. I have quick question.
I have a script that has some variables set as [SerializeField] since I want to assign them in the inspector. However, I also have a bool variable that, if false, the logic that uses those variables is not used.
So, my question would be if there is a way to, based on that bool, hide those variables from the inspector.
Use NaughtyAttributes to customize the inspector, buy/use Odin inspector, or create your own custom inspector . . .
I'll look into it, thanks.
custom inspector is an annoyance if you're constantly expanding on your data since you'll always have to edit that too to reflect changes. It's unfortunate that NaughtyAttributes is the best alternative that's free because there's still much to be desired when it comes to quick implementation of data.
Haven't seen anything built-in. You need a custom (recursive) method . . .
private static StringBuilder _getGameObjectPathSB = new StringBuilder();
public static string GetGameObjectPath(this Transform tr)
{
_getGameObjectPathSB.Clear();
int depth = 0;
void ConstructPath(Transform transform)
{
depth++;
if (transform.parent != null)
ConstructPath(transform.parent);
if (depth != 1)
_getGameObjectPathSB.Append(transform.name).Append('.');
}
ConstructPath(tr);
return _getGameObjectPathSB.ToString();
}
i think this will work
forgot to - depth
This is what I use (For Debug Only):
private static string GetPath(this Transform current)
{
if (current.parent == null)
return "/" + current.name;
return current.parent.GetPath() + "/" + current.name;
}
sb.Append(tr.name);
while (tr.parent) {
sb.Insert(0, ‘/‘);
sb.Insert(0, tr.parent.name);
tr = tr.parent;
}
Append then somehow reverse 😄
Hello, I have a list of structs. The list has a lot of entries, and I want to be able to add and remove whenever I need to. I need to send this data to a job, however, I do not know how to turn this list into a native collection. I can do this by calling '.ToArray()' and then passing that when creating a NativeArray, but that would allocate memory and would create garbage. Is there an allocation-free like with arrays in creating a native collection from a regular list?
this may give some information https://forum.unity.com/threads/collectionmarshal-asspan-support.1235407/
Greetings gentlemen, I am writing some code to spawn projectiles around my player, in a symmetrical way based on some angle calculations.
The code is here: https://hastebin.skyra.pw/ujuhamariv.pgsql
I am using a box to demonstrate my problem, as you can see it is not symmetrical at all. I am uncertain why, and I am hoping for some insight.
front facing is upwards.
i in createProjectile is simply this:
for (int i = 1; i < config.ProjectilesPerBurst + 1; i++)
CreateProjectile(i);```
NativeList?
just use nativelist at the very beginning
I load this data from a file and then I write it back to a file later. I could after loading convert the list to a native list but that would mean I would still need to convert the whole list to an array.
Try putting actual number to your angle deciding logic. Imagine what should happen when burst count is 1, 2, 3 … and compare the value with your desired result
gameObject, not GameObject.
rookie mistake, thanks
If you are just worry about ToArray overhead you can just loop the list and copy to native collection
I could get the underlying array from a list, but isn't true that the array might not be 100% accurate in terms of size? Like if I remove items from a list, the array is not resized, I think.
This would be a simple solution, but it is also not the fastest.
Why not the fastest?
does anyone know why would visual studio code intellisense stop working? i tried everything and nothing works...
You are correct, unless you use toArray which creates a new array
Typically a List has an array with a capacity bigger than the list size
Well yes, but as far as I know the resize operation is expensive so what the list does is just changes the count and leaves the array length as is
Resizing an array consists of making a whole new array of the desired size and copying the contents of the old array
Just loop and copy, foreach is optimized. If you have managed collection convert to native collection a copy is pretty much inevitable
I guess so. I would love a solution like you can do with the arrays public NativeArray<T0>(T[] array, Unity.Collections.Allocator allocator);
But instead just be able to pass a regular list when creating a native list.
Oh well
Got JSON.net working (as well as the ignore null objects setting), thanks for pointing me in the right direction @ashen yoke @plucky inlet .
One more question though, my Vector3 looks like this for some reason, any idea why?
"transform": {
"position": {
"x": 97.959,
"y": 0.5990211,
"z": 0.435000032,
"normalized": {
"x": 0.9999714,
"y": 0.00611484377,
"z": 0.004440507,
"normalized": {
"x": 0.999971449,
"y": 0.006114844,
"z": 0.00444050739,
"magnitude": 1.0,
"sqrMagnitude": 1.0
},
"magnitude": 0.99999994,
"sqrMagnitude": 0.9999999
},
"magnitude": 97.9618,
"sqrMagnitude": 9596.514
},
What json serializer are you trying
My question may be related to code, so I'm referencing it here.
#💻┃unity-talk message
Thank you for your help!
I am creating a simple script for a "Nurse" obj that follows a player, the only issue, it's that when i introduce the LookAt function the Nurse stop working as expected, it starts moving in random direction (sometimes) and not working as without the LookAt function, is anyone that can help me, I have searched through the internet but i couldn't be able to find any solution :C
This is my code
public class NurseMovement : MonoBehaviour
{
[SerializeField] private float speed = 2.0f;
private Vector3 _directionPlayer;
public GameObject player;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void LateUpdate()
{
_directionPlayer = player.transform.position - transform.position;
transform.LookAt(player.transform.position);
if (_directionPlayer.magnitude > 6)
{
Vector3 velocity = _directionPlayer.normalized * (speed * Time.deltaTime);
transform.Translate(velocity);
}
}
}```
Not really cool to spam this to multiple channels multiple times
Just because nobody solved your problem the first time doesn't mean you copy and paste it and spam it
gif
you can customize serialization
by default there is no "default" serialization for vector 3