#archived-code-general
1 messages · Page 126 of 1
hello, Ive been trying to create a system to take a list of transforms and fills out a boxcollider2D fairly evenly with them (In the stye of the stars on the american flag i guess) but Ive been having some issues creating code calculate these automatically I found this https://www.maa.org/sites/default/files/pdf/pubs/monthly_june12-stars.pdf but Ive been having some issues trying to put this into unity (idk if im even looking at the right thing) I am wondeirng if anyone can give me a pointer of where to start, thanks
what issues are you having specifically? Also you should try to specify more, like how many transforms, is it just a random number, what design specifically because theres a lot in that pdf you sent
otherwise this just sounds like looping through and placing X amount on a row with some offset, then shifting down by some amount, and repeating
Thats mainly my problem im having trouble finding resources on how to do it in the first place
Do what part though? Your problem has a few steps so try to take it step by step.
First you want the bounds of the box collider,
then you want to generate points in some fashion (for example left to right, shift down, repeat)
then place your actual objects at these points
i glance the paper. it looks like proving why 29,69,87 has no nice arrangement
My problem is finding the best shape then calculating the points
does anyone know how long it takes for firebase to delete data from the database? talking about the trash can button, i delete data, start the game and it loads the same data i just deleted
what shapes do you want? I wouldnt use this paper as reference, you should pick some designs and stick with it. Especially if you havent gotten any shape working yet
should be pretty much instantly
how much data are you deleting?
Literally one json of a struct with 2 integers
Disappears pretty much instantly on the console but when I start the game it acts like it still exists
Anyone know how I could make a backpack system that if like Ghosts of tabor and I believe into the radius where its a loose item backpack I cant seem to figure it out after doing hundreds of scripts and numerous yt vids I cant seem to find one (atleast for unity).
maybe you are still storing it somewhere, not entirely sure because i dont know your system. I do remember firebase deletions were instant from code when I used this on smaller projects.
i dont remember about from console, i only manually deleted on console if i messed up badly
i cant imagine there would be a difference though. I suggest you test this outside of unity even
after drawing up some shapes I think my main issue might just be pciking the best shape to fit the collider (based on the count of transforms to arrange) and finding a good amount of rows to fit
what are you drawing this for? if this isnt some core game mechanic, i wouldnt worry too much about having each row be perfect
as the article suggests, some numbers dont have nice representation
gift wrapping algorithm
I think the biggest issue then would be picking the correct amount of rows
i still dont really know what this is for, if its any number of transforms then you cant pick the correct amount of rows
unless you allow one row to just be different
Basically I am gonna have a grid of rectangles of various sizes and I want to be able to move a group of transform objects to a square on this grid I want it to fit in the grid box and be farely nicely spread out neatly
Anyone got any ideas to improve this code, make it more readable, easier to sort through, etc?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ManagerEvents
{
public static event Action TestEvent;
public static void InvokeMakeGrid() => TestEvent?.Invoke();
public static event Action<int> TestEvent2;
public static void InvokeMakeGrid(int a) => TestEvent2?.Invoke(a);
}```
In my last game this got extremely out of hand, I'll probably use #region stuff but wondering if there's anything else I can do
honestly i think putting TestEvent?.Invoke(); in {} is more readable, but this is 4 lines of code. I dont know what changes you really expect
I also really dont like regions unless you are just hiding 100 using statements or a massive "temporary" commented out section
I'll probably just try and use events less in this game because in my last one I kinda abused them
Also what's wrong with regions? I only recently discovered them but I like using them for collapsing large files such as player movement scripts into smaller sections like JumpChecks, GravityChecks, JumpFunctions, etc
Makes it so I can see the whole script at once
"distance between two lines" is undefined
What's a line here? Like a ray or y = mx + c?
So you have four points which make 2 lines and want to get shortest perpendicular distance between them
its annoying when im trying to find something and its just hidden inside a region. You dont see the whole script at once, you just see "JumpChecks, GravityChecks, JumpFunctions"
Generally is your problem then that the regions don't accurately describe what's inside them?
no, they're just not useful to me
i would only use them if i was in a team that used them
Fair I can see your point, I'll be very careful about using them only when needed
Im sure some people love them, but when talking about most of these conventions it can just be boiled down to "do you care enough to use it" or "does your team use it"
🤐 i dont even use _ for private variable names
Ok that I definitely don't agree with lol, love using _
I will if im in a team that does, i just dont because i hate hitting the _ key. And also because i was forced to use it in python since the naming convention is like word_word_word, ive developed a hatred for it
Anyway to improve this code?
public static bool IsEven(this int x) => x % 2 == 0;
public static bool IsEven(this float x) => x % 2 == 0;```
Probably not without overcomplicating it but might as well ask
Specifically looking for a way to not have basically two of the same function
i cant imagine how % operator works on float.
you could make it an extension so you could call number.IsEven() rather than IsEven(number).
If you're just looking to improve those 2 lines, this really isnt worth doing. Id still just put that inside a {} for readability.
also yea idk how that works on floats either
It is an extension actually, and yeah don't know if I've ever tested the float one lol
https://docs.unity3d.com/ScriptReference/Mathf.Repeat.html
apparently this exists
Yeah I'm familiar with that, what's your suggestion
oh thats just for float modulus
2x2x2x2x2x2x2x2 how do you calculate this?
use calculator
mathf.pow(8, 2); ?
look at the definition for pow
i believe pow should (base,exponent)...
https://docs.unity3d.com/ScriptReference/Mathf.Pow.html
f raised to the p
meaning yours would be 8 raised to the 2
so the way i wrote it? (8, 2)
Made an extension for Pow cause I think it's neater
public static float Pow(this float a, float pow) => Mathf.Pow(a, pow);```
pow(a,b)=a^b
What about modular power 
does anyone know how to get the gorilla tag locomotion system to pickup things throught the xr interaction layer because i tried adding like xr direct interacter to the hands including all the other things i needed and it didnt change a single thing can someone help please
i also did the grab interaction but it still didnt do anything it just basically turned it into a physics object
yes
ok thx
you multiply a for b time ie a*a*a*... then a^b, note that ^ in c# is other operator
so i shuld use mathf and not 2^8?
The built in math pow functions are faster than manual exponentation pretty sure. Dont even think c# has a operator to do it manually
Btw what do people do with various random structs that are used across their codebase? As I'm going through my previous games code looking for things to grab I'm realising I have no idea where certain structs are
Does anyone like make a class specifically for storing structs?
yeah
does anyone know about UIBuilder?
you can define struct in class and use class.struct to access it, hope it can make your code much more clear and tidy
Hi, how could I get the build target instead of the runtime platform? I need to execute a code before building the game on either platform
bro i got left in the dust💀
does anyone know how to get the gorilla tag locomotion system to pickup things throught the xr interaction layer because i tried adding like xr direct interacter to the hands including all the other things i needed and it didnt change a single thing can someone help please
i also did the grab interaction but it still didnt do anything it just basically turned it into a physics object
thanks! but is there something similar that I could get anytime before building? just something executed in edit mode
try this
https://docs.unity3d.com/ScriptReference/BuildPipeline.BuildPlayer.html
no forget that, it's setting up the build
it's just for a tiny bit of automation, i'll find a workaround :\
it should be possible. probably in an EditorPref or PlayerPref somewhere
possibly, i'll do some more research! thanks again
Not in Unity I think. Newer c# versions (.NET 7+) now combines all numbered types under INumber. You could probably combine your numbers with this.
Interesting, sounds cool
I have a struct called SFX, an IComparer sort of thing and a list of SFXs
[System.Serializable]
public struct SFX : IComparer<SFX>
{
public string Name;
public AudioClip[] Clips;
public int Compare(SFX a, SFX b)
{
char aC = a.Name.ToCharArray()[0];
char bC = b.Name.ToCharArray()[0];
if (aC > bC)
return 1;
if (aC < bC)
return -1;
return 0;
}
}
[SerializeField] List<SFX> _allSFX = new List<SFX>();
private void OnValidate()
{
_allSFX.Sort();
}
void PlaySFX(string name)
{
// Could use binary search here?, list is sorted
foreach (SFX sfx in _allSFX)
{
if (sfx.Name == name)
{
// Code
return;
}
}
}```
If I made a binary search thing for finding a SFX with a specific name in the list, would that be faster than just looping through the entire list?
Specifically looking at ToCharArray(), not sure how heavy that operation is
fisrt you have sort the _allSFX
Yeah I sort it in OnValidate, all assigns are done in the inspector
The compare function is a bit strange
You dont need recursive
You can check string .compareto
Oh my god you're right, that was pretty dumb
Some sort of recursive thing would be good probably
I override my old message…
You may need String.compare(string,string)
Then use this in your b search
Should just be as simple as this yeah?
public int Compare(SFX a, SFX b)
{
return string.Compare(a.Name, b.Name);
}```
Is there any sync tool to sync at least C# scripts between 2 folders?
I am making multiplayer game and would help out a lot if I could modify some definition on server and would change on client project too.
I know there is at least Link & Sync but it is buggy and doesn't always sync the files. It would be useful it it could also sync things like scriptable objects and their references.
I havent use this before actually so i dont know whether it will cause the sort method sort the string from “large” to “small”, but yes, just return the compared result by compare method
You should make a upm package that is used by both projects
Hmm I will check that out thanks
trying to understand composition a bit better. I have a Health script and a HealthBar script. All entities with a HealthBar need Health but not all entities with Health have a HealthBar. How do I handle this in the Health script? Right now I have this: ```public class Health : MonoBehaviour
{
[SerializeField] private int startHealth = 100;
private int health;
[SerializeField] private HealthBar healthBar;
void Awake()
{
health = startHealth;
}
public void ChangeHealth(int amount)
{
health += amount;
healthBar.SetHealth(health);
if (health <= 0)
{
Die();
}
}``` But this isn't the best approach because I shouldn't call the healthbar function on every object when not everything with health has a healthbar. What's the best approach here?
Not sure what you mean, but have you looked at ParrelSync before
How can I make a loose backpack system like in Ghosts of Tabor can I get some help please its for my VR game
perhaps you should explain how it functions for those who don't play it
Sorry so Pretty much in the backpack there is just a empty space and in that empty space is a collider and when a item is put within that collider it keeps its physical properties so things cant be placed in one another but they will sit there suspended in the air within the backpack or wherever the collider is.
lemme find a image
Empty backpackand backpack with stuff in it
and if part of the object is outside of the backpack the whole backpack will turn a certain color
Looks more like a grid based system a la Resident evil or Diablo
like this
Not physics
I dont want it like this
since I want players to have to think about their storage situation
plus this is also how all storage crates would work
If it has the grid system than there is a specific amount of stuff that can go in a backpack or a storage crate but a loose item system you can put anything in it like a hundred tiny items or 2-3 bigger items and it is more immersive for a VR game
no
Not true
It's a grid system but the size and orientation of objects matters
Ohhh
yea pretty much just without all the grids
Ye
Srry I thought u meant something like Rust
Like this
were no matter waht you can only fit a certain amount of items doesnt matter their sizes
yes that how minecraft does it too
The more basic grid system is good for flatscreen games but the loose storage like Radius or Ghosts of Tabor is better for immersive VR games
Hey, can anyone tell me how i change this so that i can look around keeping the recoil lerp. Keep in mind that in the Gun script the HandleRecoil() method is called once, and HandleKnockback() is in update. Look on the video i attached below what is happening when i try to move my mouse around.
Gun:```cs
private float targetRotationX;
private float targetRotationY;
private void HandleRecoil()
{
RecoilItemStat recoilItemStat = inventory.currentItem.GetComponent<RecoilItemStat>();
// Calculate the random recoil
float recoilX = Random.Range(-recoilItemStat.recoilX, recoilItemStat.recoilX);
float recoilY = -recoilItemStat.recoilY;
// Apply recoil to player camera rotation
targetRotationX = movement.xRotation + recoilY;
targetRotationY = movement.yRotation + recoilX;
}
private void HandleKnockback()
{
movement.xRotation = Mathf.Lerp(movement.xRotation, targetRotationX, 6 * Time.deltaTime);
movement.yRotation = Mathf.Lerp(movement.yRotation, targetRotationY, 6 * Time.deltaTime);
} Movement:cs
public void HandleMouseLook()
{
float mouseX = Input.GetAxis("Mouse X") * lookSpeedX;
float mouseY = Input.GetAxis("Mouse Y") * lookSpeedY;
xRotation -= mouseY;
yRotation += mouseX;
xRotation = Mathf.Clamp(xRotation, upperLookLimit, lowerLookLimit);
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
transform.rotation = Quaternion.Euler(0, yRotation, 0);
}
yes you still need a grid 3D or 2d or Vr @gentle rain
for what you wanna do at least
"tetris inventory" or something like that
It kinda is like that but there isnt any grids it is just empty space and stuff can go anywhere
we talking about code not visual
Yes
Oh wait nvrm
im dumb
it needs a grid system no matter what if it is visual or not I understand I think
yes
So would it be hundreds of tiny grids and then make it so the interactable would be to go inbetween the grids and so they wouldn't need to be inside specific grid(s) they can just kinda be anywhere or could it be one big grid and object can go anywhere inside that one big grid?
Rust Low poly lol looks nice
Have u played 1v1.lol before?
yeah
looks very similar but more survival based and very few games I feel can pull the low poly look off and u have done that very well
thanks
Nows time to spend the next 15 hours online figuring out how to pull off a loose item VR inventory/backpack system.
yeah i need to fix the recoil
cause you currently cant look around
i have no idea how to go around this
You want to inverse the dependency of the Health Bar/Health. You can do that by using interface. Alternatively, you can use the Observer pattern which might make more sense here.
Details (concrete implementations) should depend on abstractions.
https://en.wikipedia.org/wiki/Dependency_inversion_principle
Which problems can the observer design pattern solve?
The observer pattern addresses the following problems:A one-to-many dependency between objects should be defined without making the objects tightly coupled.
When one object changes state, an open-ended number of dependent objects should be updated automatically.
An object can notify multiple other objects.
Any VR dev Nerds out there hit me please my brain cannot handle another 20 hours of researching and trials to try and get a backpack system like this.
we love the observer pattern
(:
I have pondered about that
I presume you get leaks when you don't un-subscrube before being disposed of
Doesn't this look like 40 hours of work a table with 1 gun 1 mag and 1 hatchet
i've never thought about making a backpack system before. do the items change size when they go in the backpack, or do they stay the same?
They stay the same
sounds like the objects should just have their rigidbodies made kinematic when in the backpack
Yea but I want Volocity Tracking for the objects I think it just feels nicer because they cant go inside other objects
but would suck with attachments and mags and that stuff
velocity tracking?
Yea im bad at spelling rn
I slept till 4pm yesterday and its 8:15 am now because im trying to fix my sleep schedule
and go to bed when I get home from work at like 11pm so its gonna be a fun day of being tired
i don't know what that means, though
Ohh so umm how do I describe it, so if it hits a object like a table it just stops and doesnt go through and so if a bat hits a pile of cans the cans will go flying
that just sounds like physics :p
Yea
thank you :)
pretty much what allows this to sit on the edge and swing
can someone help please?
Is there a place to post brain storming ideas for solutions to problems?
Depends on what type of issue you are facing. If it is not code related, #💻┃unity-talk
It's a game design aspect specifically related to how I should script something
I am trying to come up with a solution on how to randomly generate dungeons. So far I have come up with the idea about creating a bunch of premade rooms to select from. Some of the rooms will have multiple entry ways. I'm thinking I should have spawn points at each entry to use those to align with each other. To spawn a new room, I was thinking I should have a "spawnroom" script attached to each spawn point, however, I'm trying to think of a way to check if there is already a room at that spawn point
Hello people, is it possible to convert a class with several lists to a JSON string ?
Honestly, just make a list of points on each room and on generation generate another room there
Lets say I have a serializable class that containts 3 public List<string> ...
Idk if JsonUtility can but Newtonsoft.Json can
I cant believe such a fundamental feature is still not implemented into Unity's JsonUtility yet...
I guess I'll try Newtonsoft then
thank you
It says Dictionary isn't supported but no mention of other generic collections
Would need to test
Well for what I've tried it is failing to convert to Json, it retuns []
Oh too bad
With List<string> and objects containing lists and other properties
Hello everyone, (I want to apologize for my English in advance)
I just joined the server, it’s in this channel that I can ask for a problem?
They really should make JsonUtility better
Yeah shoot
If its code related...
#🔎┃find-a-channel If you're not sure where to ask
did you mark it as Serializable ?
Yes
The only thing its not serializing is the list
other public propoerties are shown as expected in JSON
iirc I had to put that class inside another class or something, had the same issue but forgot the fix 😞
Yeah I recall doing something similar but it was a long time ago and I also forgot lol
maybe I parsed it or something
Thanks !
So it’s not specifically a code problem, but more with Unity, I use the IPointerHandler system and here’s what happens to me:
-
I use a unity scene that contains my camera and PhysicsRaycaster, my player and an EventSystem.
-
with this, I add an additive scene that contains different object
-
In the additive scene, I have an object containing a script that copies IPointerHandler extensions
-
The Issue is that the object with the script does not copy OnPointerEnter or other events and does not perform the functions contained in IPointerHandler.
-
Knowing that we can only have one event system, I already checked in a separate scene, the object well records events with a system events in the same scene
If anyone has a solution, or already had this problem , thank you very much.
(Sorry again for my English)
I have already been watched on forums to find an answer to my problem, or used GPT to try to get information I would have missed, but I turn a little in round, so I took the liberty of coming to ask for help here ^^"
So the problem is that when you click on the object nothing happens ?
Yep
just cruious can you show me the exact class you tried to serialize to json ?
The problem seems simple said like that, but the operation of the event system with the additive scenes remains a mystery for me currently, if it can help, a single event system works to interact with UI coming from another scene, but not scripts containing IPointerHandler
I deleted it, it was just a dummy class to test :C
sorry
Are you instantiating the additive scene after creating the scene that has the eventsystem?
oh ok was just curioous cause it worked for me maybe i did something different/wrong
void Start()
{
var save = new SaveObject();
save.AwesomeSaucesList.Add("Hello");
save.AwesomeSaucesList.Add("World");
save.AwesomeSaucesList.Add("This");
save.AwesomeSaucesList.Add("Is");
save.AwesomeSaucesList.Add("A");
save.AwesomeSaucesList.Add("Test");
save.AwesomePiestList.Add("Hello");
save.AwesomePiestList.Add("World");
save.AwesomeDawgs.Add("Woof");
save.AwesomeDawgs.Add("World");
var j = JsonUtility.ToJson(save);
File.WriteAllText(Path.Combine(Application.persistentDataPath, "Sauce") + ".json", j);
Debug.Log("Created");
}```
[Serializable]
public class SaveObject
{
public List<string> AwesomeSaucesList = new();
public List<string> AwesomePiestList = new();
public List<string> AwesomeDawgs = new();
}```
Yep, In my situation the player goes through several scenes that are added and removed with the additive system
Huh, very interesting I will give it a try thanks!
Well I don't know maybe you have to add a reference to the IPointerHandler to listen for those new scripts that you have instantiated ?
Sorry I never had to do something similar to that
So I have no relevant experience related to the problem :C
No worries, I think I’m on a very particular and very specific case
But you can change the event system that the IPointerHandler Listenning by script ?
private void SpawnEnemiesAroundPlayer(MonsterSO monsterData, int amountToSpawn, float distance)
{
float anglePerEnemy = 360f / amountToSpawn;
float angle = 0f;
for(int i = 0; i < amountToSpawn; i++)
{
Vector2 position = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right * distance;
SpawnEnemy(monsterData, position);
angle += anglePerEnemy;
}
}
Hey, this script spawn enemies around the player, to be specific around 0,0 then I add player position to the position from this function.
It takes an integer and divides 360/amountToSpawn to split a circle into x amount of angles.
So 360 enemies would be 1 degrees per enemy.
This is nice, but I need to create an oval(ideall a way to customize how squished it is)
What would be the way to do that?
I assume the trick is in distance.
you'd use the parametric equations for an ellipse:
https://www.mathopenref.com/coordparamellipse.html
You see, the difference with what I was trying to do is that you have List<string> and I was trying to convert List<object>, for example another serializable class that I had...
Example List<UserMessage> messages
@potent sleet
x = a cos t
y = b sin t```
Where `t` is the angle
And a and b are the major and minor radiuses of the ellipse
I learnt about interfaces, the observer pattern, and I decided to implement this via dynamic events, do you think its a good approach?
I am not sure what you mean by Dynamic event, however, an event is by definition the Observer Pattern.
So, yes, this should be the best way to handle the situation.
ah ok, great thank you
thanks for explaining the principle behind it and not just giving the answer :)
I will try that, thanks 😄
I don't know much about cos/sin, but if I follow this formula it might work 😄
just make sure if you're using Mathf.Sin and Mathf.Cos that you convert your degrees into radians first.
e.g.
float degrees = 180;
float radians = Mathf.Deg2Rad * degrees;
float sineResult = Mathf.Sin(radians);```
Those functions expect radians, not degrees, so if you don't convert you will have a bad time.
Yo, I've been trying Type.GetMethods() and it seems to only return an empty array no matter what if it has binding flags.
show your code
so a cos t would be x * sineResult * t? I neeed to play with it so I can figure it out 😄
MethodInfo[] meth = typeof(Additives.Weaponry.AccuracyAdditives).GetMethods();
Debug.Log(meth.DisplayContent(item => item.Name) + " " + meth.Length);
Returns all the public methods of the current Type. Says the docs.
MethodInfo[] meth = typeof(Additives.Weaponry.AccuracyAdditives).GetMethods(BindingFlags.Public);
Debug.Log(meth.DisplayContent(item => item.Name) + " " + meth.Length);
add Bindingflags.Instance
it'd be like:
float angleInRadians = angle * Mathf.Deg2Rad;
float x = Mathf.Cos(angleInRadians) * distanceA;
float y = Mathf.Sin(angleInRadians) * distanceB;
Vector2 position = new(x, y); // and then add player position to this```
distanceA and distanceB will determine the shape of your ellipse
if they're equal you'll get a circle
the more different they are the more oblong your ellipse will be
I will try this out, thanks.
Bitwise OR right? 
yes
Aight, another question, I found Unity docs not recommending Type.GetMethods. 
All usage of Reflection is slow, best not to use it if you can
That works! Thanks 😄
I guess that's granted.
Reflection is a technique of last resort.
You're giving up runtime performance and compiletime correctness
(so, basically, you're using javascript)

!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.
wew 
Yeah i do have other resort, ig i'll take it down.
this is my flashlight batter code - https://gdl.space/orilizudoj.cs
And this is my flashlight script- https://gdl.space/azavizubac.cs
Basically inside my flashlight script when i press f(activating the flashlight) I want my flashlight battery to start draining. Currently, my flashlight bar shows up when I press f but it wont drain. Could somehow help me see what I'm missing?
you call On once
you probably want to decrease the battery level in Update if the battery is being used
but it is in update in my flashlight code
does it not update every frame this way?
sure, it's in the update method
but does it run every frame? no
it runs once, when you push a button
if I do if(input.GetKey(KeyCode.f))
the battery level only changes when you call On, and you only call On once when you initially turn the flashlight (which is very reasonable)
would that work?
now the flashlight will turn on and off very very rapidly when you hold the key down
that would not help...
If that's the case, is there any way to access method attributes? 
again, make the battery drain in its Update method
No. Those must be grabbed via reflection.
this is reasonable behavior: if the battery is being used, its level goes down
alternatively, in the flashlight's update method, tell the battery to drain as long as the flashlight is turned on
I thought they'd be neat, guess not. 
This is what I would do it. It makes more sense to me.
The battery doesn't drain by itself. Something drains the battery.
public void Update()
{
On();
Off();
}
do you mean to call the function in update
in my battery script?
Why would you turn the battery on and off every frame?
The On method should do nothing but turn the battery on
yes
yes
It's something else's job to make the battery drain if it's currently on
But doesn't it run every frame when I press the f button ?
It runs once
I just named it On() without really thinking ab what its doing. It's not checking if my flashlight is actually on or off.
Make the battery remember whether it's on or off.
If it's on, drain some charge and update the UI
If it's off, do nothing
Do this in the battery's Update method.
so i should access the flashlight script in my battery script and if the bool on == true, then I should drain
and if the bool off == true I should do nothing
Sure. I would have the flashlight just set the on/off bool on the battery directly.
That way, the battery doesn't need to talk to the flashlight
or honestly I could combine the scripts
Sure.
just separate out the parts that change whether you're on or off from the parts that use that information
There's no way to shorten this, yeah?
#if UNITY_EDITOR
if (_disableScreenShake)
return;
#endif```
hey ppl how do i go about keeping the voxel world generation on a level height for 4x4 area and than go to the next value in the noise map??
are you trying to add an editor-only screenshake toggle?
perfect it works. I really appreciate your help.
Application.isEditor tells you if you're in the editor
Oh that's much nicer thanks
lots of useful stuff in that class
Anyone have any luck returning the URL+ Parameters in a WebGL build? I have a Jslib file that is returning the correct URL but not the parameters.
public void Squash() => StartCoroutine(C_SqaushStretch(1f, new Vector2(-0.5f, 0.5f)));
public void Stretch() => StartCoroutine(C_SqaushStretch(0.4f, new Vector2(0.1f, -0.1f)));
IEnumerator C_SqaushStretch(float dur, Vector2 mag)
{
if (_squashing)
yield break;
_squashing = true;
float elapsed = 0;
Vector2 start = transform.localScale;
while (elapsed < dur)
{
float humped = ManagerExtensions.HumpCurveV2(elapsed / dur, 1);
transform.localScale = start + humped * mag;
Debug.Log(humped + " " + elapsed / dur);
elapsed += Time.deltaTime;
yield return null;
}
transform.localScale = start;
_squashing = false;
}```
This is a coroutine to squash and stretch
The first Debug message to the console starts with elapsed/dur being 0
Then the second is 0.33333
And from there it counts up like normal
Anyone know why?
This is what HumpCurveV2 is:
public static float HumpCurveV2(float t, float a) => -4 * a * Mathf.Pow(t - 0.5f, 2) + a;```
That's working fine
Can somebody please help me creating a POST webrequest? I get error 422
Ok weird I changed nothing and it's suddenly working. Not sure what happened there but whatever
- Another c# syntax question of mine:
- I have a generic wrapper class called Observable that emits an event whenever a value inside this wrapper is changed. Now the part that i don't like is that i have to reveal an extra property to work with an actual value instead of just directly assigning it. So can i achieve the following syntax?
Observable<int> myInt = new Observable<int>(10);
// casting to underlying T type, i.e. int
int i = myInt; // i is now 10
// casting int to observable wrapper
myInt = 5; // no new instance, the same object with modified underlying value
- I read about this a little, answering some possible solutions: "=" operator cannot be overriden; implicit casting from int to observable requires me to create a new instance - not an option because allocations; cannot be converted to struct because it will be boxed anyway
you can't override assignment, yeah
this ain't C++ 
i have so many goddamn pensive cowboy emojis
how to use perlinoise in increments of for for voxel generation?
it should only change the x,y,z in increments of 4
Can someone review this code? for some reason the entervehicle function works, but the exit one doesnt ```using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VehicleSeat : MonoBehaviour
{
VehicleSeatCtrl vsc;
public enum SeatType{ Gunner, Driver, Passenger }
public SeatType seatType;
private void Start()
{
vsc = GetComponent<VehicleSeatCtrl>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.F))
{
vsc.enabled = true;
vsc.ExitVehicle();
}
}
}private void EnterVehicle()
{
vs.enabled = true;
enterPos = playerObject.transform;
playerObject.GetComponent<CharacterController>().enabled = false;
playerObject.transform.SetParent(transform, true);
playerObject.transform.localPosition = Vector3.zero;
playerObject.transform.localRotation = Quaternion.identity;
playerObject.GetComponent<ChatController>().disableMovement = true;
playerObject.GetComponent<ChatController>().disableOther = true;
this.enabled = false;
}
public void ExitVehicle()
{
playerObject.GetComponent<ChatController>().disableMovement = false;
playerObject.GetComponent<ChatController>().disableOther = false;
playerObject.transform.SetParent(null, false);
playerObject.transform.position = enterPos.position;
playerObject.transform.rotation = Quaternion.identity;
playerObject.GetComponent<CharacterController>().enabled = true;
vs.enabled = false;
}
and what does "works" mean?
it does as the code says, enters the vehicle(keeps player scale, disabled movement) on the exit it doesnt keep its scale and it messes up the disbeling
okay, that's more useful than "doesn't work"
nvm, found problems
hey there, I am getting wonky results from raycast, where I am trying to test room bounds using them, but they're not returning the way they're supposed to be
the two red dots are supposed to be testing the height of the room, on a perfectly aligned wall, its hitting before the ground
Unclear what your rays are
where are you casting from
the player
gimme a second, let me post the code
this is context-free. use Debug.DrawLine to show the rays you're casting
or Debug.DrawRay
you also said "the two dots" but I see 4 in the image
the ones that are atop each other
go take a few minutes to get a nice-looking screenshot with all of the information we need
alr
purple lines are tested room bounds, red dots are the raycast hits, red lines are the raycasts them selves
on the top hit, there's a ceiling, I am just hiding it in scene view
so where are you expecting these dots to be exactly?
the one bellow it, is supposed to be hitting the ground, but for some reason its hitting mid way on the wall
The raycasts are still a little unclear to me. I see one going from the camera to the wall. but the others are like... along the wals?
can you show the code?
including the code that draws the red lines and dots
hits 1, 2, 3, 4 and 5 test the room's length and width, while hits 6 and 7 test the room's height
To be clear you're expecting this dot to be down here?
where's the code that draws the dots?
in draw gizmo
can you show it?
But the line is hitting above that, no?
Gizmos.color = Color.red;
foreach (var corner in corners)
{
Gizmos.DrawSphere(corner.point, 0.25f);
}```
exactly
what does this have to do with all the code above?
its supposed to hit the ceiling, then hit the floor
you told me to show the code that draws the dots
where does corners get populated? Can you just share the whole script in a paste site?
yeah but you're missing pieces
hard to tell what's going on when I don't see the whole picture
corners are the raycast hits
Can you just share the whole script in a paste site?
you're not actually drawing the first hit anywhere
corners[0] = hit2;
corners[1] = hit3;
corners[2] = hit4;
corners[3] = hit5;
corners[4] = hit6;
corners[5] = hit7;```
none of these are hit1
its not really important because its always level with the players head
also drawing them with different colors or labels might help
because right now impossible to tell which is which really
anyway - the way you're doing this is pretty weird - casting these rays "skimming" the walls really tightly is possibly causing issues
I could see the engine tripping up and registering a hit along the wall somewhere random
are you just trying to get the corner points of the room?
basically
Couldn't you just. cast in all 6 directions from the player?
That will give you the bounds
that wouldn't really give me the actual room bounds, since the might be somthing obstructing the actual walls
something like:
Bounds b = new(transform.position, Vector3.zero);
Vector3 directions = new Vector3[] { Vector3.up, Vector3.left, Vector3.right, Vector3.down, Vector3.back, Vector3.forward};
foreach (var direction in directions) {
// do a raycast
if (Physics.Raycast(blah blah) {
b.Encapsulate(hit.point);
}
}
// now b is your room bounds```
isn't that still possible with your current method? Can't you just get around that by using a layer mask on the raycast?
I just want to know why the raycast is skiming the wall, is there any way to circumvent that?
well you're firing the ray from impossibly close to the wall
do it from... not that close
add an offset?
maybe
I think my approach is a lot simpler but sure
another possibility is your colliders are not actually lined up with the renderers
you should double check the collider gizmos to make sure
they're the default cubes
I'm working on procedural room generation and don't know where to start. Any tips? (2D, room map should look like tree branching)
so what are you trying to do, again?
not "shoot raycasts"
what property of the world are you trying to learn?
is the room always a rectangular prism?
its suppose to
just ignore everything that isn't level geometry
put the walls on their own layer
when you do this, you'll have to make sure that the six raycasts are aligned with the axes of the room
if your rooms are always axis-aligned, then that's a non-issue
all the rooms will be aligned with world axes
of course, if the ray goes through a door, that won't be quite right
how are these rooms constructed?
using default cubes
Yeh just gonna suggest this again:
#archived-code-general message
With the benefit of giving you a nice Bounds object at the end
well I am not going to use this code in unity, I am only using unity for prototyping
that's why bounds.encapsulate won't help
what?
?
then you aren't going to be using raycasts either...
no I am going to use raycasts
but you siad you aren't going to be making this in unity
and unity gives you raycasts...
raycasts aren't exclusive to unity
(neither is the concept of a bounding box, mind you...)
I am messing around, trying shit out
we will happily help you with things in the context of unity, but if you're going to just ignore the (very reasonable) solutions offered because they're unity-specific, then we're wasting our time here
the code still doesn't work in the context of unity either way
Hello guys i'm new here, and i need a little help. In some games like AC, there's a feature when you move the joystick slightly then the character will do the walking and if you push the joystick all the way up/down they will run. How can i replicate this feature?
at the most basic level, that's just how an analog input works
you get a vector whose length depends on how far the stick is pushed over
so if you base the player's velocity off of that vector, you'll get walking, then running
If you're asking about the animation, that's going to be blend trees
Blendtrees let you smoothly blend between many different animations.
so there's no way of replicate that on a keyboard ?
oh, you want to do it on a keyboard
well, keys are digital: they're pressed or they're not
typically you have some extra modifiers to run or walk
e.g. holding shift makes you run
ok thx
It's just a bunch of Max / Min calls then to create the two Vector3 extreme corners that define the bounds.
Either way the raycasting technique I showed is relevant
thank you, I'll try it out, I seem to be missing something either way
set the interpolation on your rigidbody component
Hi i'm trying to make a game that ill later compile to webgl, i'm using HttpClient from the .net framework to make requests to a backend server but since async is not supported i tried using the HttpClient.Send(data); in order for it to work. This method appears in the official microsoft documentation for HttpClient but i get an error that this method is not defined ```
error CS1061: 'HttpClient' does not contain a definition for 'Send' and no accessible extension method 'Send' accepting a first argument of type 'HttpClient' could be found (are you missing a using directive or an assembly reference?)
this is the code
public HttpClient httpClient;
public CookieContainer cookieContainer;
cookieContainer = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler { CookieContainer = cookieContainer };
httpClient = new HttpClient(handler);
string body = "{ "message": "test" }";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://127.0.0.1:8080/api/test");
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
var response = httpClient.Send(request);
using var stream = response.Content.ReadAsStream();
return JsonUtility.FromJson<GeneralResponse>(stream);
can anyone help me, either help me fix it or tell me any other lib i could use for sync comunication?
Send method is not available in .net framework
sorry System.Net.Http
i;m dumb XD check https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.send?view=net-7.0
i see other people recommending this method in stackoverflow too
but you can make HTTP request in the .net framework using HttpClient.SendAsync method
will this work in webgl after? when i tried to build and run it didnt
i want synchronous requests, await async is not supported in webgl Async/Await Unity only supports the main thread on WebGL as per their documentation. This means you can't use Async/Await operations, and you need to perform these on the main thread instead. One way to do that is by using Coroutines.
Give yourself a visible nickname
Well then it doesn't work
why
XD
I don't have to explain why, it's obvious
its a good name
But in the event that you truly are not able to understand why, it's because it creates confusion who's talking. Which is what I assume troll accounts with no visible name intend to do.
Im not a troll
Anyway, give yourself a visible name.
this is a better name
idk why my coding is so much different then videos i watch, i figured i could just copy all the same things they wrote, but i dont have all those extra options when typing out certain code. For instance, when they type "Using UnityEngine.InputSystem" I never had the option to press tab to quick fill like it was already recognized what I was trying to type. ALSO alot of my code stays white or just turns green, when the videos is blue or greyed out or yellow. I typed out all the code just for it to say it has no reference. Like idk what im doing wrong or if i dont have the correct unity plugins installed. Plus i dont get all those "unity message references" when im trying to write code. Can anyone help? im using visual studio aswell
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
why not use UnityWebRequest?
ty
I know I shouldn't be getting hung up on this, but I keep coming back and thinking what's the best approach for this. I ended up using this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Health))]
public class Hittable : MonoBehaviour
{
private Health health;
private Knockbackable knockback;
private void Awake()
{
health = GetComponent<Health>();
knockback = GetComponent<Knockbackable>();
}
public void TakeHit(int damage, int knockbackPower, Vector3 knockbackSource)
{
TakeDamage(damage);
if (knockback != null)
{
knockback.InflictKnockback(knockbackSource, knockbackPower);
}
}
public void TakeDamage(int amount)
{
health.ChangeHealth(-1 * amount);
}
}
But I feel like hittable shouldn't be aware of knockbackable's existence. I first tried using UnityEvents but it seemed messy trying to pass Vector3 as a parameter. I also tried an IHittable interface but it doesn't seem suitable in this case.
Have hittable fire a C# event
and Knockbackable listen to it
I feel like Hittable should be aware of Knockable. Being knockback is in the definition of a Hit.
What about, for instance, if I have a box that remains stationary when hit
Perhaps some enum to check if it can be knocked back
You can knockback something that is not being hit, however being knockback does not mean you have been hit.
I think the logic like this seems a bit too split
then you just don't attach the knockbackable
You can also, modulate the knockback effect inside the knockback component.
So it is ok to GetComponent<Knockbackable> in Awake() if I can't guarantee that the component will have knockbackable?
I only ask because I feel like (if knockback != null) is messy
it's ok to, but you don't have to if you use events
i'll give this a go
Checking if the interface exists is widely used
you can also use TryGetComponent and inline it
It's not like you're checking it every frame anyway
Hey! I would put this question in a more skybox-related chat, but I think it'll have to do more with coding than anything in engine.
I'm trying to make my skybox move dynamically with the player's vertical position. So the higher up the player ascends, the more the skybox will transform down to mirror that movement. This is to better sell the feeling of moving upwards as well as revealing the higher bits of the skybox to the camera. Any ideas on how I would go about doing this?
as a rule skyboxes don't move. The only real way to make them move would be to use a custom shader for the skybox which you can pass a parameter (like player height) into.
Hmmm, alright then
I don't know anything about shader coding so that might be a little bit tricky
i tried using events, but now when an enemy takes knockback the player also takes knockback
am i using the wrong type of event?
sounds like you used a static event or something
impossible to say without seeing your code
ah yeah that was the issue, thanks
Here's a fun thing I've encountered recently. When running my app in fullscreen on mac, the menu bar used to show up when the user hovered near the top of the screen. Now all of a sudden it doesn't do that. Does anyone know if there's a specific setting for this to be enabled? All 4 fullscreenmodes seem not to do this anymore
sounds like a mac os setting
Yeah I thought that too, but we've tried it on several macs all with different os versions so we can narrow it down to something has changed with the software. It used to show on all systems in our last version. However we removed all the references to the resolution from the project. I've looked through version control and I can't see a reference to any setting that would do this.
For clarity I'm talking about the window title bar, with close/minimise/maximise on it
I can also see the dock when I hover over, just not the title bar...
i'll see how mine behaves the next time i test a built
what's your unity version, etc.?
Does anyone know how exactly the double jump in hollow knight works? It's not like a normal jump, it sort of holds or goes down slightly or something before being lauched up. Or is that just a trick being played on my eyes from the animation?
Also anyone know any tips to make double jumps feel extra juicy and add game feel? (From code, not effects/visuals)
juiciness/game feel is often largely the realm of animations
though yes the physics of the movement are also important
I had a script called Gatherable and one called Hittable which described rocks and enemies respectively. however i realised Gatherable is almost exactly the same as Hittable so I decided to merge it into Hittable. Whereas previously Gatherable objects could only be destroyed by a pickaxe, now they can be destroyed by gunfire. What's the best way to differentiate between the damage types? from reading up on similar situations where info such as "fire damage" and "water damage" is needed, an enum seems suitable. is that correct for my situation?
Yes, or you can handle it from the weapon/tool
bitwise enum
thanks
that's a better read actually
Useful for checking multiple types at once, and it has inspector support
Hey so i use Perlin Noice to geneerate a voxel map "like minecraft" but i want a "block" to be out of 4x4x4 voxels
can someone help me out here?
i thought about adding a loop to keep x/y/z on 1 value for 4 repeatisions but i have no idea how 😄
make your main for loops add 4 each time instead of 1 to your x y and z values, then do 3 inner loops for x y z that go from 0 to 4 (exclusive) to fill all 64 voxels with the same type
for (var x = 0; x < chunkSize; x += 4)
for (var y = 0; y < chunkSize; y += 4)
for (var z = 0; z < chunkSize; z += 4) {
Set4x4Voxels(x, y, z, yourVoxelType);
}
private void Set4x4Voxels(int rootX, int rootY, int rootZ, VoxelType voxelType) {
for (var x = 0; x < 4; x++)
for (var y = 0; y < 4; y++)
for (var z = 0; z < 4; z++) {
SetVoxel(rootX + x, rootY + y, rootZ + z, voxelType);
}
}
thats my current gen code https://pastebin.com/va0fJqs2
so i would have to do a loop with x+4 as main and than do a loop for x < 4?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i think i get it... will do some testing 😄 thanks ! ❤️
need to edit my function, you have to add the parameters to the for loop values, sec
but yeah that's the basic idea
you would want your chunk size to be divisible by 4 though
i think about 16x16x512 so 1 chunk would be 4x4x128 blocks 😄
can i get back to you if i fail and give up? xD
maybe
lul thanks ❤️
I am new to unity so can anyone please help me with a jumpscare. The ai has to come and attack me to trigger the jumpscare but I don't know how to do that
2020.3.29f1, note that it was working before in this version, sifting through other parts of the version control history to see if I can spot anything that was maybe removed earlier.
As a side note, I came across a deprecated option PlayerSettings.macFullscreenMode has an enum called FullscreenWindowWithDockAndMenuBar. I don't know if there's a newer equivalent to this setting or not, but it would be useful if there was
https://www.youtube.com/watch?v=gx0Lt4tCDE0 i guess thats something you want?
In this video we take a look at how to build a Custom Event System in Unity. We look at why a Custom Event System might be useful for your game, and the advantages that building one might have over using singletons, or relying on dependencies in the inspector.
Be sure to LIKE and SUBSCRIBE if you enjoyed this guide! Share the video for extra lo...
Yes but I don’t know how to do any of that stuff
thats a tutorial you can follow 😄
Sounds like you should be starting smaller
I’ve been using unity for 5 years already but I just started coding… I used to be the one that would copy and paste everything I want.
oh damn
well still i use tutorials for most stuff and started to "understand" what i do in code recently 😄
i think Code Monkey is nice for beginning to code
Yea… I’ll just try to figure it out
good luck! 😄 hope you learn fast 😉
Thx
I'm trying to alter properties on a material depending on a variable, (for example, depending on whether or not the object is selected), but I heard I should not just set material properties directly.
As this either creates a new material entirely, or alters the material property for all objects using that material
I want to create a VR app in unity. This is the plan:
3d modeling a room
Add some visual monitors
Then I want to put it on my phone. I want to connect the app with a PC (if needed with a PC application. I also can create the connect application my own) and have some visual screens for my PC on my phone VR app. And then I have like 3 visual monitors and I can configurer these on my PC.... Like this windows settings where you can move the monitors so it's lined up
I know it's a bigggggg goal....
How to display it in unity on to the screen? How to add visual monitors?
What is the correct way to interact with materials through code?
Asked chat gpt... Doest worked... Sorry for wierd sentences
What are you planning to display on these monitors?
I should be like normal connected monitors... Just visual
What I'm getting is that you want to like, show your PC monitor on your phone screen, right?
Yes.. in my 3d project on a screen model
You're kind of asking too big a question at once. "How do I do the entire project"
multiple cameras each targeting a different display
Ok wait
I would suggest you try to break it down into smaller doable parts
I have a 3d modeled room with monitor models etc. Now I want to create a PC application to create multiple visual monitors and schow these screens in the 3d models of the screens.
Which you want to display on your phone, right?
-
How to create multiple visual monitors using a application on the PC
-
How to display these on the 3d models in unity
Yes
So, a good first step would be to try to get a VR app that runs on your phone
I got
which shows your 3d modeled room and screens, with nothing on them yet
I follow https://youtu.be/qZzhXHqXM-g
▶ Grab the code on patreon : https://www.patreon.com/ValemVR
▶ Join the discord channel : https://discord.gg/5uhRegs
If you want to get started with Virtual Reality and don't have money for a VR headset, this is the video for you. I'll get through all the step to develop your first VR app using your mobile device in a VR Cardboard headset, the ...
Right
That's step one, right
Ok
Step two then is to get your phone to talk to the computer at all
So if the screens are displaying just, text from the computer, that's step two completed
Then step 3 is to make the computer make these images of the monitors and send them to your phone
Without the controller in the hand and if possible with other monitors... So it's a new and not duplicatimg the physically one
your example uses Virtual Desktop which has a standalone application that captures and streams the desktop to the receiver app. This standalone app is not something you would be able to (or even want to) create in unity
also I don't know if you've ever actually used it, but you need a really good wifi connection for it to work smoothly
actually what he wants to do is not that difficult but it does require a very serious skill level to implement correctly
Nah Maybe start with 1. And I would like to use a cable
anyone knows what extension is being used here to show more info of a certain method or function
Change your editor in the unity settings
let me guess, you're using unconfigured vs code?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
And open it by double tap
Probably a good idea to avoid VS code to begin with..
don't quite understand what you mean by unconfigured but I suppose so. I downloaded vs code manually though (not that experienced with coding yet)
raising a generation of programmers that code blindly, with no debugging
Change your unity settings
do yourself a favor and switch to visual studio community. it's far easier to get working correctly and much less likely to just randomly break. and is actually still supported by unity, vs code support was dropped recently(ish)
Unity suggests you use "Visual Studio" which is a different application from "Visual Studio Code". Unless you are really used to Visual Studio code or want a specific feature from it, I suggest you switch
there are more steps required than just simply changing the one setting in unity. hence why i used the command for the bot to post the guides
is there any practical difference between the two?
yeah
they are completely separate programs. vs code is basically just a fancy text editor while visual studio is a fully featured IDE out of the box
Unity has much tighter integration with Visual Studio, which is the important part here
I see, I'll listen to your advice then and switch coz doesn't matter much to me what I use as long as it makes things convenient
just make sure to go through the guide to get it configured for use with unity. #archived-code-general message
I was surprised at how convenient it was to set up and make work, coming from Unreal which constantly fights with visual studio
ok will do, thanks
the big thing you lose with VSCode is a debugger that works correctly
How would I change this dropdown for a URP material at runtime in a script? I have tried to google for it but I can only find standard pipeline shaders or shader graph shaders, and this is neither.
So I figured it out, I was unaware that Screen.SetResolution(int,int,bool) isn't the only overload.
What I should have been using was Screen.SetResolution(int,int,FullScreenMode.MaximizedWindow)
I'm just confused as to how the old code had this behaviour when this was never specified. Guess it's just one of those things
Can you help me then? I want to create only one for beginning.
!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.
Why?
pretty sure they used the command for themself
yes
Can't use that second one, it's UnityEditor
sorry, no. I said you would require a very serious skill level which you obviously do not possess
just curious why u need to even swap it at runtime? This sounds like a weird approach
Toggling a wall
Or anything really
I want to swap between opaque, semi-transparent, and disabled without needing two copies of every material
semi-transparent being the issue here
you can setup your own shader with a node going into its alpha channel, then just decrease the alpha. Or apply a dithering, transparent setting really really sucks
Disabling and opaque work fine
Fihgting with this surface mode thing is making me think that doubling materials is probably easier
KISS
My first time using properties. This isn't working. I assume its my use of Time.time?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Recoil : MonoBehaviour
{
private bool recoil = false;
public bool InRecoil
{
get
{
if (recoil && Time.time >= recoilTimer)
{
recoil = false;
return false;
}
else
{
return true;
}
}
set
{
recoilTimer = Time.time + recoilTime;
recoil = true;
}
}
private float recoilTimer;
[SerializeField] private float recoilTime = 0.3f;
}
It's used here :
public void Shoot()
{
// Check if recoil period is over
if (!recoil.InRecoil)
{
// Shoot raycast and return hit object (or null)
RaycastHit2D hit = Physics2D.Raycast(firePoint.position, firePoint.right, range);
// If the ray hit an object, check if the object is Hittable
if (hit)
{
GameObject hitObject = hit.transform.gameObject;
TryHitObject(hitObject);
}
// Enable recoil period
recoil.InRecoil = false;
shotFired.Invoke();
}
}
I would definitely just use a custom opaque shader graph if you want a gradual decrease from opaque to invisible, then just change the alpha value. The transparent setting does not write to depth, so you get some weird rendering issues sometimes.
I did this, because transparent gave me very bad rendering issues
Unity's URP renderer feature is something to look into as well
not
recoil = true;
but
recoil = value;
@naive swallow
https://youtu.be/vmLIy62Gsnk?t=690
Learn how you can easily fade out objects that are using the standard URP shaders that obstruct view to the player using C# code!
In this tutorial you'll see how to determine which material properties to adjust for the standard URP shaders:
⚫ Universal Render Pipeline/Lit
⚫ Universal Render Pipeline/Complex Lit
⚫ Universal Render Pipeline/Simpl...
follow the timestamp
looks promising
So here's the thing. It's not as simple as just making another material and referencing it in the inspector, the materials are loaded from an asset bundle exported by a different project and applied to runtime-generated meshes using data from a java program that parses AutoCAD drawings so if I could just hit a transparent button it would be significantly less work because if I change one of these materials that's every one of those repositories that needs to be updated to make sure it threads all the way through to Unity
yeah that would be a pain.. I'd def look into the video I sent seems the enum is there , I've seen the same one in a forum post but this one's recent
cheers mate
that video looks more tedious than just making a shadergraph. Also I have no clue whats happening in your setup digiholic lol
What I use Unity for can legally be considered a "War Crime"
not quite sure why you have a java front end though, I just parse AutoCad files directly in Unity
Because that part of the pipeline was written fifteen years ago and has about six people actively working with
lol, gotta love legacy shit which no one understands anymore
thats how those 6 devs keep their job
if no one understands it, no one can replace them
I mean, most of us understand it. It's not generated solely to be consumed by Unity. My program is sort of a leech on the data pipeline that siphons off bits of it to display in a modern graphical form instead of basically spreadsheets
tell me about it, my bank account loves it, Cobol support anyone?
!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.
cycleOffset is a weird variable.
Right now I'm trying to have an animation play from the beginning on its first loop, then play from a second in on all subsequent loops. But instead, cycleOffset just changes what time the animation gets transitioned into and then loops the animation like regular from there. Pretty much the exact opposite of what I want, lol.
Could someone show me how to do a sort of inverse cycleOffset?
Hello! Simple question, does anyone know how to detect if the player is moving down? I'm trying to do something like this:
float slopeDotProduct = Vector3.Dot(slopeHit.normal, Vector3.back);
Debug.Log(slopeDotProduct);
if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, groundRaycastDistance, groundLayer))
{
slopeAngle = Vector3.Angle(slopeHit.normal, Vector3.up);
if (slopeAngle > 0f && slopeAngle <= slopeAngleDefault)
{
if ((slopeDotProduct < 1 ))
{
isFalling = true;
}
}
I'm trying to detect if the player is moving down a slope. If the player is moving down a slope, an animation would play until they hit the ground.
Checking the slope of the ground won't tell you if the player is moving down, unless your player can only move in one direction
You could check save the last y position and compare it to the current see if it went down then update your animation.
and the player would have to be grounded
Is there any way to start playing an animation during a transition?
I've named my transition states appropriately, and Animator.StringToHash() works fine with it, but Animator.Play tells me that it "couldn't be found".
show the code and the error
and screenshots of your animator state machine
myAnimator.Play(Animator.StringToHash("TransitionToReload"));```
one sec for the screenshot
All I'm trying to do is dynamically construct a freeze frame at the transition's normalized time
I know how to get the info, I just can't figure out how to construct it
Play takes the name of a State not a transition
I'm well aware. I was more or less asking for a possible solution
rigging something with crossfade might be the only solution
Would someone be able to teach me what the right application is for creating functions that have <T> in them? I'm not sure how to quite word this into google to get the explanation I'm looking for and I'm trying to figure out if that would be best suited for a function I'm making
would it be right to say you use it almost exclusively to relay to said function a specific class? I feel like that can't be right though because if that was the case you could just make it a parameter
its called generics
but that can't be right cos it needs to return something
<T> is a generic argument
ah okay
that's more googleable lmao
ahh okay thats exactly what i was trying to find
thank you lmao
in essense when you create generics you are creating a template
the compiler will then compile that class for you into a specific version of whatever you provide as T
so List<string> List<int> are two separate classes, the compiler will generate them when you create a List<T> of string or int
so would you say the distinction is more of an optimisation thing than a functional difference in the code
or am i mistaking what you're saying
For methods, it's similar. For example, GetComponent<T> is actually a way of writing GetRigidbody GetCollider GetLight without actually writing the same code 400 times
well, you get the benefit of exactly the same api of the whole family of List<T> disregarding the end type of T
it's so you don't have to write the same function N number of times just replacing a type
the optimization part only applies to structs you pass as T
since when T is a struct, a compiler will generate a type with that struct, bypassing boxing costs
i'm just trying to figure out the difference of doing it the generics way and doing it by just passing a type through as a parameter
generics happens at compile time
parameters happen at runtime
ah so it isn't actually a functional difference? functional as in like, changes the behaviour
and I guess if you're using type parameters you'd be doing reflection?
you'd have to show an example of what you're comparing
yeah generics enforce validity of your code and class compatibility at compile time
you wont get that if you will rely on casting
because I don't really see how you would do the same thing with generics vs a parameter
its like what if GetComponent instead took an argument for the type of component you want
There is an overlaod that does just that
rather than doing it with generics
this will do a bunch of runtime checks
you cant enforce that the type you pass is inheriting Component
at compile time
you wouldn't get compile time type checking
with generics you just add a constraint where T : Component and you know at compile time if you passed the wrong type
you would have to do this:
Component c = GetComponent(typeof(Rigidbody));
Rigidbody r = (Rigidbody)c;```
vs:
Rigidbody r = GetComponent<Rigidbody>();```
GetComponent<Vector3>() wont compile
okay i think im getting it
also yes you can enforce type constraints like that^
lol it actually does compile
so its kinda like all the restrictions of what can be passed through are hard-coded for this
but for different unrelated reasons
Unity could make it not compile but they didn't
largely because they want GetComponent to work with interfaces
yeah
Imagine if you could only have List without a generic type
why imagine
you would have to cast the object coming out of it every time
there are still remnants of .net 2.0 in System
in the List case that's like an object though right, please excuse my poor ass understanding of this language it's extremely hodge-podge
i wouldnt generally group it together with something like GetComponent in my head but
i guess im just not really sure what List is to the program, rather just what it does
List is an object that contains a bunch of other objects
yeah okay
List<int> is a list of ints
a wrapper around an array with specific way to handle inserts/removes
List<GameObject> is a list of GameObjects
if it wasn't an object containing objects i wouldve had to reevaluate my entire understanding of how C# works lmfao
it is an object, its a class
its just that the compiler generates a new separate class for each T you provide
so like, is this another reason why generics are useful, or is there a similarity between GetComponent and List that im unaware of
yeah
ok List<int>.Add(int value)
see the int value
that is compiler generated
enforced
oh okay
in the source its Add(T value)
i think i get what you're saying
both use generics, both are unrelated to each other
yeah okay that's not something you could do with just passing parameters
thats making a lot more sense
generics really isnt as complicated as it seems, its notation is just confusing at first
the most confusing part i see is when to use them
unfortunately that also means it looks like the use for it I have right now turns out to not be the right use case, and im gonna have to try and remind myself of this later if it eventually does prove itself useful
that comes over time when you realize you actually need that functionality
it really is niche
and has lots of pitfalls
i feel like ive said so many things are niche by now lol
i still would advice to overuse them at first
overuse, learn when it does and doesnt work, find that middle
at the moment im working on a script for tracking trigger collisions on the player and a function that, when called, will return the nearest active collision
i was thinking "what is that <T> thing about and is it applicable here" but i dont think generics will work now knowing what they're intended for
im not sure if this is a bad approach but i've been using tags to detect collisions between categories of things in the game anyways, mostly because I'm scared of GetComponent calls
oh actually I do have another question
if I've got a component where, say for example the parent of the script will always have a certain component that I want to cache in a variable, but I don't want to have to manually drag the component into it from the inspector for each instance, what do I do?
because I'm scared of GetComponent calls
i advice to drop this thinking asap
the obvious thing is to just do GetComponent call in Start
but i hate when the first frame of the scene loading has a giant lag spike
and when I do this for literally every script i think that might be a genuine concern
so like is there a way to do it so that it assigns this reference on build?
before you continue with this logic, did you profile and see a giant lag spike caused by your scripts?
this is just what has happened in past projects
that lag spike is most likely unrelated to any get component calls
is it really that huge of a myth
yes
i have heard a lot of pushback on the idea that GetComponent calls are expensive
the only problem is my computer is rather powerful
and i feel like it's not going to accurately portray how it would run on weaker hardware
this wont matter, run more get comps then
Check how many you need before you notice major lag, it will be an absurd amount
test right now and see how extremely high the amount of GetComp calls you can get away with are
oh yeah
this seems useful for saving time tho
This doesn't really matter. OOP is expensive in general and the real bottleneck lies in the bandwidth between your CPU (cache) and your RAM. It doesn't matter what clock speed your processor runs at.
CPUs aren't designed to jump around in memory like OOP does
Even if you tested this on a shit PC, i guarantee you wont be calling enough get components per frame no matter what
this only matters if you have like 1000s of entities fighting and calling per collision
where did this initial crazy getcomponent stigma come from i wonder
unity has been around for a while
stigma's exist on everything
yeah nah in this case it's literally only the 1 player
people say Vscode is light weight => people say every other IDE is "heavy"
wtf does "heavy" mean because i showed someone my spotify took more resources than VS
People don't understand nuance. They respond better to hard rules
e.g.
me ;)
aww
This conversation is pretty pointless. It's always going to be faster to access a cached reference to a memory location than to search for it
i think the problem here is that in my head i assume this means that its important
How do interfaces work with getComponent anyway? Does it do the same linear search between scripts?
but from what ive heard generally with games its more important to get shit working quickly
Why wouldn't it be important?
If you can save some CPU time with minimal effort, do it
yeah, but minimal effort is the stipulation
manually assigning variable references in the inspector for a bunch of objects takes a lot of time
well i was just trying to say, dont be avoiding GetComponent if you have to use it. If you can cache something then just do it
No it doesn't. And if it's for a list of things, you would automate that.
public class GetCompTest : MonoBehaviour
{
public int count = 1_000_000;
void Start()
{
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<Animation>();
}
void Update()
{
for (int i = 0; i < count; i++)
{
if(TryGetComponent<Animation>(out var a))
{
if (a)
a.animatePhysics = !a.animatePhysics;
}
}
}
}
what does this code do
on my machine 5k getcomps per frame take about 1.2ms
This is why you always start searching from the middle of the array
heats up your users PC
1_000_000;
TIL you can do that
50% chance you find it faster 50% worst case ;)
so if i were to allocate a budget for a very dynamic crazy architecture that needs those 5k getcomps every frame i could estimate
in realistic scenarios where its really easier and better architecturally to use getcomp, you would end up with about 100 per frame
i think tbh most of the lag in my games have been GPU time anyways
which is peanuts
CPU bottlenecks will come very fast in unity.
depends how complicated your game is
it's done in native code, but I don't see why it would be any different
https://github.com/Unity-Technologies/UnityCsReference/blob/18e481fd5dbda630b82f4f4c59a2a0164ed75ebd/Runtime/Export/Scripting/Component.bindings.cs#LL45C91-L45C91
if you're using update a lot i'd imagine thats true
atm i generally try to avoid update as much as I can get away with though
Ah, that's understandable. I'll probably have to refactor some of my collision checking since it's mostly done using interfaces on larger gameobjects.
its most likely just linear search
oh uh
any other type resolution structure would be insane
its probably also worthing that I'm using interfaces a fair bit for the collision checking
good
im still pretty new to using interfaces but i kinda get what they are for
use what makes sense architecturally
collision checking and raycast stuff usually a bulk of work my project does
and pathfinding
its very easy to optimize clear simple code, its very hard to deoptimize a mess made on wrong assumptions
thats a good thing to keep in mind
you should also avoid multithreading. Unity doesn't support it, unless its through the jobs system.
i used to use it
everyone just goes "well I'll make my game super fast by dividing the logic on all cores" not realizing that you literally cant
cos I thought I needed to
i think there was one case where I did actually make good use of it
or ending up paying more for context switch
Multithreading works best when you have linear data, and you simply give your thread a memory address to work on
there was an object that had skinned mesh renderer and i wanted to have it continuously animate by having the points follow a wave function based on time
and using the jobs system for multiple transforms is super easy
since it was purely a visual thing it made a lot of sense
and its meant to run on mobile archetecture
did you benchmark it?
but yeah i never actually did
preemptive optimisation
conceptually it just sounds wrong to run everything on a single thread
unity does background stuff on other threads
so I thought "well this ParralelForTransform thing is designed to iterate over multiple transforms using a seperate thread, and this application is purely visual"
it was all stupid though cos it took way more time than it probably needed to
and only one of that object would ever exist in the entire scene
and it probably didnt even need to animate unless it was in the player's field of view
hey i have three prefabs
and a empty game object
is there a way i can replace the empty game object with a prefab
based on a certain keypress
What do you mean by replace?
once you instantiate its a new object
but idk how to reset the placeholder object
everytime i do keydown
should i delete the instantiate object
keep a reference to it and then destroy it
you basically make a clone right
currentObject = Instantiate(etc..
sum like that
then you can do if(currentObject != null) Destroy(currentObject)
rinse and repeat
oh ok
probably want to learn how to do object pooling though 😛
Destroying and Instantiating every time get costly
is that when i run it through a for loop
It's when garbage collector cleans up after the object is destroyed - expense.
can someone help me get a xr direct interactor work with the sr grab interactable because it never wants to pickup anything when i configure it correctly
!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.
Having trouble with interfaces. I had a few questions earlier in the day that I posted to the beginner chat, and they said it might be more advanced, so i'm posting my followup here.
I've got an interface IAbility that all of my ability cards derive from. When the player selects a card to use, the game controller has to be able to call the 'activate' method without knowing the name of the class of the card. Thus: trying to use interfaces to keep method names uniform but method effects unique.
However, when I want to call on a method in one of my derived classes, the Debug log is telling me that I'm actually running the version of the method that exists in IAbility, not the version that exists in the GameObject Ability_Attack
So: If I have GameObject activeAbility, how do I get the game controller code to find the right component in activeAbility.GetComponent<?????>().activate()?
I tried IAbility where the ?????s are, and it doesn't work.
I can't hardcode it to be activeAbility.GetComponent<Ability_Attack>, because that means it'll only work for that one type of card.
Thanks
interfaces don't have implementations, so based on your description you've done something wrong. I would guess that you have a non-virtual method defined in a class (not interface), and then implemented a method of the same name in a subclass and ignored the compiler's warning about it
we would need to see some code snippets to be sure though
The Interface:
The attack:
where the method is called:
First two lines of the loop are to instantiate the attack ability based on the prefab, and then swap out the reference to the prefab in favor of the instantiated version
Since when can interfaces define implementation?🤔
What I get in my debug log is the "Template" text
that was my reaction too, apparently it's a thing: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
you shouldnt get anything
that wont compile
Oh. Does unity support C# 8 already though?
I don't know, but if he's using something unsupported it would explain weird behavior
delete those implementations in the interface Greg, and see if it works as expected
Unity support for C# 8 has started on version 2020.2 and C# 9 has started on version 2021.2
thing is they support features that are compatible with their mono
and you have to explicitly enable it
Greg did you enable c# 8 support?
I have no idea. I followed the default install, I thought.
How would I check?
Try making the interface protected virtual.
jesus
And override in your sub class
close visual studio, delete .vs folder in project root, in unity Preferences > External tools > regenerate project
If you want a class to implement interface methods, then in the interface, these methods should not declare a body
In your example they do, which is incorrect in this context and won't do what you want them to do
Interface: void GenerateTargets();
Wait, regenerating the project seems to have cleared up the "virtual is not valid" error [edit] nevermind, it's back
They use default interface implementation.
So I did that, and now it hates my Ability_Attack class [edit] OK, cleared up those errors.
It works!
So should I still try reinstalling Unity/VirtualStudio? Sounds like this C# version issue might cause problems down the line
But thanks everyone! This was really helpful!
No. I don't think the issue was with the version at all. It was probably an incorrect usage of the interface default methods.
It sounds like i can write default methods for the things that all of the ability cards will have in common, then. I'll try playing around with it.
They need to be used like virtual methods in base classes(you need to override then in the implementing class). Or so it seems from reading the docs.
Anyways, tip: don't use features that you don't know much about. Or at least read the documentation before that.
It does work, as the more recent posts in that thread mention.
Oooh, defining some base implementation with interfaces sounds nice, assuming you can append to the logic
Actually, I guess you can just make the methods virtual and override them anyway
ah, but it would be nice between unrelated classes
Has anyone ever ran into the issue where uploading their game to steam for some reason disables certain features of Unity? When I build my game locally, light cookies on my directional light behaves like expected, but when I upload that exact same build to steam and play it through steam, the light cookies magically disapear...
Is it possible to check if splines intersect. I have multiple splines in the same 2d plane. I want to find the intersection points. I use dreamteck splines
Message dreamteck
Anyone here who managed to create an axis indicator at the bottom left? Trying to figure out how
this?
Yeah! I want to always keep it on the bottom left in the game view. To show axis
Been trying out a couple things, a 3D model with a second camera, but it's not shown for some reason
Ahh I mean that it is in the game view, not scene view. As in within the game
lol.. then state what you're actually trying to do properly 😄
Why StopCoroutine("coroutine_name") doesnt work?
Sorry, may not have been really clear indeed 🙂
you need to cache a reference to a coroutine when you start it
- you need to reference it
So string attribute just doesnt work as it should be?
nope, and is a bad way to be coding anyway
Dept is bigger than the main camera and the second is a child, normally it would show 🤔
Okay, thank you.
move this to #💻┃unity-talk , this is a code channel