#archived-code-general
1 messages · Page 69 of 1
How can i do for do the whole update thread ?
ok sad.
if you want to stop your object from running code every update call, put a bool and if(myBool) return;
So how can i stop the update for no go further
You dont
Why do you want to
just return early.
I want when i disable nav mesh agent obstacle for my AI because i need to wait the next frame for mesh update.
That works depending on context yeah
i can't return becuse the code is on function called from update.
not on update himself
while(true) {
;
}
will suspend your update thread 🤡
Just return a bool that tells if you should return or not, somethinf like that
yeah the way to go is to only run your function if you really want to.
and not to start suspending things
Here is my script i need to stop the update loop when i disable the nav mesh agent obstacle for wait the next frame.
https://github.com/pytchoun/UnityCodeReview/blob/main/Scripts/AI/ZombieController.cs
Yes, I mentioned as well. It is vague. Instantiate using CreateInstance or all instantiation (using developers through CreateInstance + in loading scenes by unity)
No, Coroutines run in the "background" and the delay will have no impact. That said, are you sure you want to invoke your coroutine in Update? It will invoke each frame.
You add a boolean "isRunning" and return; the Update method at the start when it's true. Set it to true and the Update will not invoke anything in it.
Considering you already have a guard clause in the Update method it should not be hard to make another check for the navmesh agent. I see there is a class-scoped variable you disable so you can check that.
Unless it's not your code? 🤔
if condition and class field
You already have a check in there using return;, and you have a variable in your class you can check
Seems pretty simple to add another check.
Yea return if dead.
which variable ?
The navmesh agent you disable.
Hey does anyone know how to encode a string into a bytes array?
First result on google: https://www.c-sharpcorner.com/article/c-sharp-string-to-byte-array/
using System.Text.Encoding
thanks. Sorry I should have included that I need a method for encoding function calls and their parameters within smart contracts
I'm not exactly sure what that means
Yes it's probably too specific but I'm attempting to supply a multicall function on the ethereum blockchain with bytes array data
Sounds interesting. I'm not sure I can help tho 🤷♂️
fair enough, thanks anyway
Is there any way I can hook into an asset duplication event?
I want to change some serialized fields to be a different value when something is duplicated
Ideally I want to have access to the original asset as well as the new one
apologies for the hissing + clicking, i need to fix my audio filters
So the player character is connected to a central point by a LineRenderer, and I'm trying to get it to wrap around obstacles, which it mostly does well. The issue is that, with small objects, it's not sticking, and is instead triggering the unwrap function. The current implementation I'm using is:
{ropePositions.RemoveAt(ropePositions.Count - 2);}```
where *ropePositions.Count -1* is the player, -2 is the most recent line connection, and -3 is the second most recent.
So in instances like in the video, where you can raycast to both of the two most recent line segments, it removes the most recent segment.
My previous solution involved measuring the angle between the three points, but that seems to have caused more issues, making certain points stick too well instead. So I need some way of more accurately telling the line when to come unstuck.
oh discord doesnt like mkvs. ill convert it
Dont think there is a event specifically for an asset being duplicated, but there is an event for when an asset gets imported, duplicating an asset should cause an import, maybe one of the post processors is what your looking for:
https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
Thanks! Ill look into it
Are your objects gonna be able to disappear as well?
ideally there'll eventually be physics puzzles and maybe some sort of consumable resources, yeah, so down the line i'll also need to figure out how to manage that, since if i pull one of the sticks out of the ground the line hangs in the air until i move around it
I would consider moving back the line path and do more casts maybe.
You would want to have some minimal size of the object you can use for delta how far back on the path you move.
Then you may find that you collide to a new object that you insert in the list instead.
smaller steps does sound like it'd be useful down the line for simulating a more rope-like behaviour
my next idea was closer to pic but it doesn't feel very adaptable
You can also consider doing circle/sphere casts for narrowing it down and not having to do too many casts ( I would do this once I know that a shape has dissapeared).
So I would go for delta back as the red line in my image, and do that for each segment. If that fails to hit, possibly do some bigger sphere/circle cast to see if there are any objects blocking and then narrow it down.
I'm familiar with deltaTime, but i'm not quite getting what you mean by delta back. like, a percentage of the distance between the two points?
Lets say you define your smallest radius of a shape to be size X, then you could go distance X (Half diameter) back on the line to be sure you would not miss a shape to do a cast to see if you have free vision to next point.
oh i see, that makes sense
How can I pass any type of parameter in a method? Is that possible? Something like this: ```cs
public void Method(AnyType _value)
{
}```
You'll want to look up the concept of generics
Thank you 🙏
I doubt an SO can have scene references
you can also use the type object
SoundClips and Prefabs are not in Scene Scope while things out of your hierarchy are in scene scope. Your Scriptable Object is a dataset and therefore also not part of the scene per se
You want a generic public field for any script, did I get that right?
You cant directly serialise a generic to the inspector
You could try, as others suggested, to go with the type object or monobehaviour if they are all monos, but they have to share some base class or interface.
https://hatebin.com/igsaymagee
so i've got this so far - took the distance between the last two points, normalized it, and added those two points as further checks before removing line segments, but lastPoint is still being removed as before, so i'm not sure what's gone wrong there
Thanks
Technically, you could. It'll show the weird error/missing text but it'll have the Metadata for it. Not smth to use or rely on though bc it doesn't work all the time . . .
Is your minimum radius 1?
How can I pass something as the Type?
Right now if you're Hitting anything on the ray it's removing it.
I've never tried, was just assuming it'd be the same as is for prefabs
hey, which one was it ?
if I wanted to round float to the highiest int/whole number
example.
int objs = 41;
int boxCapacity = 10;
int boxRequired = 41/10; // this is a float "4.1", right ? ... how to make the result 5 not 4 ?
thanks !
yeah the sticks are width 1, so i figured turning the direction into a unit vector and multiplying it from there as needed would fit
It's wrong
Alright, as long as you know it^^
It's ceil Mathf.Ceil()
oh yeah , i have just noticed , thanks 😄
I have a sprite property on a ScriptableObject, I use this sprite as the icon for the object when instantiating it.
Its basically a list entry which is generated like so:
public class FishListEntry : MonoBehaviour
{
public Sprite FishImage;
public string FishName;
public string FishAmount;
[SerializeField] private Image FishImageField;
[SerializeField] private TMP_Text FishNameField;
[SerializeField] private TMP_Text AmountField;
private void Populate()
{
FishImageField.sprite = FishImage.sprite;
FishNameField.text = FishName;
AmountField.text = FishAmount;
}
}```
Now when I try to set the FishImage property it says "NotSupportedException" the code for that looks like this:
```cs
FishListEntry fle = go.GetComponent<FishListEntry>();
fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;
Where the group is a grouping of the individual controllers, and "fish" is the SO holding the information for that specific object
TL;DR:
I have a sprite as a property on an SO, I reference an instance of that SO (not the SO itself) and want the sprite of that instance to be displayed on my image component
you could use a generic method:
void Method<T>(...) {
// T is the type
}
not correct btw >> that gave me 4 not 5
Oh. That's because you're dividing with integers
int / int = int
Do this: cs (float)myInt / myInt2
This will equal a float
That you then can Ceil
https://pastebin.com/EUD98MYs hmm... this system seems to be letting some button mashing through. canInput is set to true on every beat
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.
u were right 😄 , but i used CeilToInt because i wanted an int
I'm working on a save system for my inventory, and I need to save a list of item (scriptable object) and amounts for each inventory box. Basically I would like to make a dictionary that can take two separete variable as the value, what would be the best way to do this?
thanks ❤️
Sprite.sprite?
You're getting component of an SO? It doesn't have components does it?
problem is the delta casts aren't doing anything - delta is definitely on the opposite side from the player, there shouldnt be any way for that cast to return true
Where did I say component on SO? Even if thats just nitpicking but I think I clearly stated the sprite is a property on an SO and I want the sprite property from the SO to be applied on an image component
You're leaving code out. But I assumed FishController is an SO? And you're getting it by "GetComponent<T>" ?
No, FishController is a Controller, or in other words, a Behaviour, Fish is the SO, specifically group.FirstOrDefault().GetComponent<FishController>().fish is that SO in question
Use debug drawline to see where the lines are
So Sprite is the name of your SO?
Right mb.
can we see the FishController code?
cuz at the moment I think it's the fact that Image doesn't exist in fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;
typeof()
which in your case is
typeof(2) or typeof(int) as 2 is an int
Would assume something is breaking on "group.FirstOrDefault()" probably best to post the full error as well for better help.
I think there's been a misunderstanding. I need to access the value. The value of any type
object o
Type t = o.GetType()
?
public class FishController : MonoBehaviour
{
public float speed = 1;
public bool direction = true;
public Fish fish;
// Update is called once per frame
void Update()
{
transform.position = new Vector3(transform.position.x + speed * (direction ? 1 : -1) * Time.deltaTime, transform.position.y, 0);
gameObject.GetComponent<SpriteRenderer>().flipX = direction;
if(!direction && transform.position.x < -8)
{
direction = true;
}
else if(direction && transform.position.x > 8)
{
direction = false;
}
}
}```
You can box it in object, but that's not really something you usually want to do as it's expensive.
What's the most performant way to recast fx. a float as an int?
and what is inside of Fish?
Because I see you are doing fish.Image
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Fish", menuName = "ScriptableObject/Fish", order = 1)]
public class Fish : Item
{
[SerializeField] private string fishName;
public string FishName
{
get
{
return fishName;
}
set
{
fishName = value;
}
}
[SerializeField] private float size;
public float Size
{
get
{
if (size == 0)
{
size = Random.Range(minSize, maxSize);
}
return size;
}
}
[SerializeField] private float minSize;
public float MinSize
{
get
{
return minSize;
}
set
{
minSize = value;
}
}
[SerializeField] private float maxSize;
public float MaxSize
{
get
{
return maxSize;
}
set
{
maxSize = value;
}
}
[SerializeField] private float speed;
public float Speed
{
get
{
return speed;
}
set
{
speed = value;
}
}
[SerializeField] private float priceMultiplier;
public float PriceMultiplier
{
get
{
return priceMultiplier;
}
set
{
priceMultiplier = value;
}
}
public float ActualPrice
{
get
{
return SellValue * Size * PriceMultiplier;
}
}
// How likely the fish is to appear once.
// If fish appears rarity check will be done again until fish once doesnt appear.
[SerializeField] private float rarity;
public float Rarity
{
get
{
return rarity;
}
set
{
rarity = value;
}
}
[SerializeField] private Vector2 depths;
public Vector2 Depths
{
get
{
return depths;
}
set
{
depths = value;
}
}
[SerializeField] private GameObject prefab;
public GameObject Prefab
{
get
{
return prefab;
}
set
{
prefab = value;
}
}
[SerializeField] private Sprite image;
public Sprite Image
{
get
{
return image;
}
set
{
image = value;
}
}
}
Its just a property nothing more
So fx. cs MyMethod((float) 2); MyMethod((int) 2); MyMethod(transform);
and
void MyMethod(object o) { }
yes
Genius. Thank you 🙏 I think I know what to do
I think this is way more interesting then
SpanFish.65 is the "fle.FishImage = group.FirstOrDefault().GetComponent<FishController>().fish.Image;" line?
interesting
SpawnFish.65, yes
The Seven Deadly Seas fishing update?
okay just eyeballing this and seeing you have a library, i don't know if this tool can extrude meshes with holes. you also have to choose the right faces
it's not Maya
player.position to delta 100% hits the pillar so it shouldnt be removing anything
i meant of the actual game so i can get a sense for what it looks like
Can you send your code again?
Pls @ mention me in any replies, need to pick up my gf, so I wont miss them when Im back
https://hatebin.com/igsaymagee
i did also try changing the linecasts to raycasts in case that made a difference but nothing seemed to change
You did not fix the boolean logic for removal I mentioned.
I'm trying to figure it out, but at this point I think the best action is trying to create a single fish (not in a group), and then trying to change only that one fish's sprite to rule out that the error comes from groups.
Then if it's still only a scriptable object error oof I don't know why.
The only thing I would try changing for now is the Image name in the Fish : Item class because unity already has a definition for Image to maybe something like fImage (f for fish) or anything else
@prime acorn
Right now IF both linecasts are hitting the object, it WILL remove the line vertex.
i have triangulated it and have the vertacies, but I am not sure exactly how to choose the right triangles?
ah mb i getcha now, i think i might have gotten myself mixed up with raycasts
so i've set them to if (!Linecast)
Good news: fixes the snapping
Bad news: if the line touches the same shape twice in a row, it gets stuck and -i assume - can't come loose because the linecasts hit the shape they're 'stuck' to and then stop
Make sure you nudge it out of the object.
hmmm... tiny OverlapSphere to find the nearest terrain object and then moving it 0.01 units away?
Many ways, but depends how you add the points right now. if you're finding the pure edges or just takes the point where you hit the ray to the object etc.
just takes the point where the linecast terminated
maybe i should make it find the edges so i can physics stuff later tho
Is there an easy way to get an element of an enum by using an index? fx. cs public enum PlayerState { Idle, Walking, Falling, Crouching } In this case I want PlayerState[0] to be PlayerState.Idle, PlayerState[1] to be PlayerState.Walking, etc.
Is that a thing with enums?
Or do I need an instance of it?
So this might cause issues when you're moving fast etc. One easy way if dealing with squares and circles that are symmetric around their center is to just either have fixed offset from center or apply an offset - since it will always be pointing in the correct normal direction outwards from the edge where you hit. If you're dealing with more complex shapes you would want to find the edge in some way to either look up vertices or do multiple casts.
hmm... well what is your goal
what are you trying to do
Enums are numerated from 0, you can also assign each enum value a number e.g. Idle = 3
How? cs PlayerState test = PlayerState[0];?
oh, nice. Thank you
Not even sure if you need to cast it, can probably assign directly from integer as it is it's backing type.
Just wondering if it was possible. I don't need it tbh
yeah, at one point the player was triggering new segments when they were moving too fast 😄 but yeah i definitely dont want to be going too fast regardless
i'm still only mucking about with basic shapes for now, but i'll plan for complex shapes
i'm sure there's some way to instantiate an empty game object at the point of impact as a child of the pillar or similar, then have the linerenderer track it
alternatively, i might place some premade transforms on the prefabs for my level objects and just check which one is closest to the impact - in the case of the pillar, one for each corner and middle of each vertex should be fine
i'll sleep on it for now cause it's late, but thank you very much, i greatly appreciate the help you have given me today
Hey, I need help converting a number.
I have a float that ranges between 0-2. I need to convert that float to a number that ranges from 0-100, but reversed. For example, if the float was 2, I want it converted to 0. If it was 0, I want to convert it to 100. How would I do this?
math
I found my error its so dumb and was actually lacking context lmao
IGrouping<string, Fish>
this is my group
guess what
my Fish SO of course has no MB component as it was trying to get lmao
i'm still looking for a fix or an alternative method if anyone has one btw
I have quick question, I am trying to make an simple AI that will essentially just be state machine with 3-4 different states.
My idea of state machine is just to have switch case for each state,
But I been looking around and I see people handling their states with use of Animator, making most state transitions on animation end.
Can someone guide me to what best practice/approach would be ?
This is for a enemy that detects player, walks to them and initiates a fight like in dark souls but without complexity.
(-100 * (yourNum*.5)) + 100
Thanks, I'll try that.
sorry for so many edits, that should be the last one 🙃
I have a script: cs public class CharacterInput : MonoBehaviour { public Vector2 moveInput; public bool jump; }
I then have two other scripts deriving from CharacterInput: cs public class PlayerInput : CharacterInput { KeyCode jumpKey; private void Update() { if (Input.GetKey(jumpKey) { jump = true; } else { jump = false; } } } and cs public class CPUInput : CharacterInput { private void Update() { // Use neural network to calculate input } }
From a third script I want to use GetComponent() ```cs
public class CharacterMovement : MonoBehaviour
{
CharacterInput inputData;
private void Start()
{
inputData = GetComponent<CharacterInput>();
}
private void Update()
{
if (inputData.jump)
{
Debug.Log("Jumped");
}
}
}```
Will GetComponent<CharacterInput>(); return whichever one of the classes PlayerInput and CPUInput it finds attached to the game object? And how can I modify a field that is local to PlayerInput from CharacterMovement?
the .5 normalizes your number from 0 to 2, to 0 to 1. Then you figure out how much to subtract from your max amount
Thank you.
Shouldn't it be something along the lines of:
(1 - x / 2) * 100
?
"why the hell does my spaceship keep accelerating downwards, how did i mess up the AI"
yeah the AI just reached its target and went to idle, not zeroing out the gravity any more
i didn’t think it could be simplified further, but you’re right 😅
Can I start a coroutine by invoking a UnityEvent?
Would (1 - x * .5) * 100 be faster? Is multiplying by .5 faster than dividing by 2?
yes multiplication in general is faster than division, but if its not running a million times per update, dont worry
also your compiler will do magic anyways, so without looking at the assembly code, you cant tell whats going on anyways
Aight. Thanks
the only relevant performance thing is: dont use Math.Pow if you can use x*x
Wait why not?
because its for general exponent calculation and takes much longer
like, factor 20 or sth
exponents and square roots are expensive.
Why .main.startColor doesnt works?
If you hover your mouse over the red line, what does it say?
this is not a variable
but...
SpriteRenderer.material.color is of type Color while ParticleSystem.main.startColor is of type ParticleSystem.MinMaxGradient
ParticleSystem parSys = new ParticleSystem();
SpriteRenderer ren = new SpriteRenderer();
ParticleSystem.MainModule main = parSys.main;
main.startColor = ren.material.color;``` This somehow works
ParticleSystem parSys = new ParticleSystem();
SpriteRenderer ren = new SpriteRenderer();
parSys.main.startColor = ren.material.color;``` But this doesn't
Can someone explain why?
like that?
var main = particleCollision.main
ooh, thank you :p
You're welcome 😊
the compiler should be smart enough to compile it to bit shift left 1 >> 1 (for ints at least)
Oh right. Does that work with float calculation as well?
i was about to amend that
Ahah okay
i’m not sure what it how it would optimize it for doubles
but better to assume the compiler knows best
Definitely. Saves me the hassle
Assets\TsTubeMove.cs(26,20): error CS1061: 'List<GameObject>' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'List<GameObject>' could be found (are you missing a using directive or an assembly reference?)
help?
List<GameObject> doesn’t have a .transform but GameObject does
so remove < and >?
no
why are you using a list?
are you trying to store one object or multiple?
Replace List<GameObject> with just GameObject
a list is a collection of GameObjects
so figure out why that errored
Assets\TsTubeMove.cs(26,18): error CS1061: 'GameObject' does not contain a definition for 'tranform' and no accessible extension method 'tranform' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
says that
Try spelling "transform" correctly
tranform isn’t a word
@hybrid flare you should configure your editor so it underlines the errors and helps give potential fixes
!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.
i tried that idk how to do it
did you install visual studio through unity hub or online?
online
alright
How to Create Cube Skin save system?
ayy did it thanks
is there a way to pause all code mid game?
like if they die or somthing
not exactly a pause, but you can set Time.timeScale to 0 and it basically freezes anything that relies on time delta to move
ah perfect
Hi,
how do I get the key of a directory?
//
Dictionary<Car, int> cars = new Dictionary<car, int>();
for(int i = 0; i< cars .Count; i++)
{
Car _car = cars[i] //???
}
You foreach, as Dictionaries usually don't have int indices
Here, you'd need to pass a Car to retrieve the int value bound to it
foreach (KeyValuePair<Car,int>
If you need the Car from an int, then your Dictionary is backwards, or you're not using it properly
@knotty sun @simple egret Thanks a lot ❤️
nah , I need to loop through all of them regardless ❤️
For some reason, my code is generating the same random numbers every time it is run:
float randPosX = Random.Range(-6000f, 6000f);
float randPosY = Random.Range(-6000f, 6000f);
Debug.Log($"Twister {idx} - Random X: {randPosX} Random Y: {randPosY}");
For more context, I start 3 coroutines that each call the same function where the above code is
Each coroutine generates a different random X and Y, but it's the same each time I run the game
Twister 0 - Random X: -1798.52 Random Y: -1830.727
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)
Twister 1 - Random X: -5659.34 Random Y: -73.58789
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)
Twister 2 - Random X: 2916.033 Random Y: 991.0547
UnityEngine.Debug:Log (object)
Tornado:GeneratePreSpawnData (int) (at Assets/CustomAssemblies/Twisters/Tornado.cs:248)
TornadoSpawnController:Start () (at Assets/CustomAssemblies/Twisters/TornadoSpawnController.cs:102)
If I stop the editor and re-run the game, I will get the same output
Is it possible to get a tile on a tilemap when it is using something other than 0 as a z level?
getTile() does not seem to allow this.
Ask in #🖼️┃2d-tools
Anybody got any advice for custom tiles. Say I wanted the player to place a tile, for example a factory tile. Which has a coroutine which basically just does something every X seconds.
So I create a custom tile, but there is no method 'OnTilePlace' or something like that which I can override to start a corouitine? Any ideas?
Is the only option to add the method to the tile and call the method when it gets placed?
example code:
tilemap.SetTile(tile)
tile.StartTimer()
I want to draw a line in screenspace, is it possible to do that with the line renderer?
How can I make a script that when you press a button you go to a new scene
You'll probably find the answer by copy and pasting your message to Google. Create a component with a method calling SceneManager.LoadScene and hook it up to the click event in button inspector.
Thanks but I already figured it out!
Is it possible to convert a TKey to int? I have a dict that uses an enum as a key and I need to get the element of the enum. Idk if dictionaries store anything in a order as a list or array though
hey guys, im trying to code a lazer script where there are 3 parts of the lazer, the top. the bottom, and the main lazer middle, and if you move the bottom, then the middle will rotate/ stretch to always be linked with it, but for some reason, the middle part always rotates 90 degrees and then rotates
and the stretching doesnt work
If it's an enum you can just cast it to int
int myInt = (int)myEnumValue;```
"TKey" doesn't actually mean anything. It's just the name of Dictionary's generic type parameter
Have you thought about using a LineRenderer?
whats that
So if let's say an enum has 3 diff values
Red
Green
Blue
And there is colors associated to each enum, red for red, blue for blue and green for green (let's call this someDict). if i make an array with the same colors in the same order (let's call this someArray), and i would want to compare if they are the same in some function, would it return true?
Compare(someDict((int)Red));
bool Compare(int element)
{
return someDict[Red] == someArray[element];
}
edit: [] not ()
hope this makes any sense, im just experimenting with things atm
I have no idea what someDict((int)Red) means
is someDict a function?
is someArray a function?
they are written like functions in your example
some random Dictionary
How is it defined?
same for SomeArray, a random Color32 array
Dictionary<SomeColorEnum, Color32> i would guess where SomeColorEnum is the Enum with the 3 values
I think maybe here's the thing you're missing
enum Color {
Red,
Green,
Blue
}```
This is implicitly the same as:
```cs
enum Color : int {
Red = 0,
Green = 1,
Blue = 2
}```
so this:
bool example = Color.Red == (Color)0;
bool example2 = Color.Green == (Color)1;
bool example3 = (int)Color.Blue == 2;```
would all be true
enums are basically just a way to add fancy names to numerical values
they are stored by default as int, and can easily be converted via casting to and from int with that defined value.
By default they are numbered 0, 1, 2, etc... in the order they appear in the enum definition
yeah i got all that, but im just wondering how to compare an object in dictionary and an object in an array if one of them uses an Enum as a key and an int as a key, because with arrays i could make so that the second element is Red and it would automatically break then?
so i'd have to order things exactly in the same order in the array as the order of the values in the enum in order for it to be correct when comparing or whatever?
I don't think the array and dictionary are even relevant here
Dictionaries don't have an order
arrays do
yea exactly
so I'm a bit unclear what you're asking about here
this pretty much
I'm not sure what kind of comparison you're talking about though
if Red is the first value in the enum, would the color red need to be at element 0 in the array?
forget the comparison thing, i just took an example
You're saying if you want the array to work the same as the dict?
lemme think on how to explain this
Then whatever you mapped to Color.Red in the dictionary should be the first element in the array, yes.
I don't really understand why you would have both a Dictionary and an Array in this situation though
what would be the point of having both?
This is declaring a three dimensional array of int called data
Since it's in parentheses I can only assume it's a parameter in a function or something.
Similar to float x; < just a data type and a variable name
Ohhh I see, is there any other way to initialize the array as 3 dimensional without ,,?
no
well there's jagged arrays
but that's a slightly different things
e.g. int[][][]
I see
I want to convert that to a native array for processing in burst, is that possible?
Yes
just flatten it
all multidimensional arrays can be flattened to a 1D array
Then you just do a little math with the / and % operators to convert your 3D index to a 1D index
Because I made a menu manager system that basically switches between GameObjects (stored in an array) and it switches to the menu corresponding to the index I pass in the menu switching method. I was thinking of using this method generically so if I were to have for instance a pause menu or a main menu, I'd use it there. It has a constructor so it knows what menus are in it
I have, however, a method in a different class that takes in a GameMode enum which does different things (gets called by buttons), but should also show the right game mode settings menu (for customizing a match). problem is the enum/int problem I have right now since I am taking in an enum but it needs an int to switch menus. so I just made a dictionary with the same key (GameMode enum) that stores these menu objects and I just need to switch to the right menu corresponding to the selected game mode
Looks complex, I will give it a try, thanks!
So, if I have a singleton script, do I need to attach it to a game object and have it in my scene? It keeps telling me that I have an object reference not set to an instance of an object all the time.
Depends on how you are implementing the singleton. If you are relying on Awake or some other Unity callback to set it up, yes.
Man. Singletons are confusing as hell.
try to stay away from them as much as possible tbh, often you don't actually need singletons if you just structure your code better.
They make it very easy to start accidentally writing classes that have multiple responsibilities
and you want to stick to the Single Responsibility Principle as much as possible.
Anyway, does anyone know why one of my components returns null when added?
They both extend from UnifyBehaviour which extends from MonoBehaviour
oh I think I figured it out.. it has something to do with my assembly references
I had the FooMono behaviour in my edit mode test folder
it's kind of weird that it just becomes null instead of throwing me an error...
I cannot think of a solution to my problem other than singletons. Have to keep a persistent score and variables for multiple objects that are also accessible from multiple objects.
a persistent score and variables for multiple objects that are also accesible from multiple objects?
wah?
can you give a more concrete example?
You can roll with one singleton, aka service locator pattern ( a bit more too it), you can roll with events (static or SO), you can roll with dependency injection (either something fancy zenject/extenject or by unity inspector/FindGameObject)
I noticed that after I lock my cursor, I get a large pointer delta afterwards the first time I move in my LateUpdate camera movement.
I tried skipping a frame which worked for normal update but not this time, still getting a large jump
extenject is no longer being maintained
i've been working on a replacement DI framework
aiming for it to be a little less of a learning curve
it won't be as extensive though
if youre interested i can dm you the repo
guys I cant access TransformAspect, its giving an error that it cant be found
private readonly TransformAspect _tras;
i have included the using Unity.Transforms;
Show code, are you using assembly definitions?
no one has commented they are having issues with this so Im assuming it worked for them
sorry this doesnt show here
Do you only get the errors in VS, or are they also there in your Unity Console?
also in console
Assets\Scripts\Component\JellyAspect.cs(11,42): error SGA0007: Aspects cannot contain instance fields of type other than RefRW<IComponentData>, RefRO<IComponentData>, EnabledRefRW<IComponentData>, EnabledRefRO<IComponentData>, DynamicBuffer<T>, or Entity. ()
this is the error
Oh yeah that's not your usual C# error
yeah 🥶
the other error is this
Assets\Scripts\Component\JellyAspect.cs(11,26): error CS0246: The type or namespace name 'TransformAspect' could not be found (are you missing a using directive or an assembly reference?)
but in this document they are using this
https://docs.unity.cn/Packages/com.unity.entities@1.0/manual/transform-aspect.html
Are you using assembly definitions?
I dont know what that means
if your asking if this is a library built by unity then yes
Ok. It's having an .asmdef file by your scripts to make it compiled into its own assembly file. If you do, you need to reference the transform package with this.
I dont get it but okay XD
private readonly Unity.Transforms.TransformAspect _tras;
like this?
If you didn't create it it's not the issue, no worries.
yeah 😢
Did you install the entities package?
yes
which versiopn
Hi everyone! I was wondering if anyone could help me on a raycast thirdperson issue. Basically my raycast shoots to the centre of the world (no idea why)(Video: https://www.dropbox.com/s/qst0c00mgn6wzzr/Unity_mVZHCyrHU1.mp4?dl=0)
cam = GameObject.Find("MainCamera").GetComponent<Camera>();
Debug.DrawLine(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance, pickupLayer))
1.0.0
cam.transform.forward is not a position
So it doesn't make sense to use it in DrawLine
it's a direction vector
If you want to provide a direction vector, use DrawRay
DrawLine expects two positions
DrawRay expects a position and a direction
I was using that before but it doesn't show where it lands
You need to conditionally draw different things when it hits or doesn't hit
How do I do that?
when it hits you can do a DrawLine between the ray origin and the raycast hit
when it doesn't, do the normal DrawRay
Conditional code can be written with if and else in C#
Do you have the code to drawline?
wdym
Using DrawLine and DrawRay as we have been discussing 🤔
When I use DrawRay it's like 2cm long
It's as long as you tell it to be
perhaps you should use pickupDistance as the length of the ray
is
private readonly RefRW<LocalToWorld> localToWorld;
the same as
private readonly TransformAspect localToWorld;
no
oh okay 😢 thanks
one has type RefRW<LocalToWorld> and the other has type TransformAspect
transformaspect is not being accessed, I think it has been removed or my library is corrupted maybe?
Debug.DrawRay(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance))//, pickupLayer))
{
It was removed
why did you comment out the layermask?
So that the if statement can hit anything so it's true
I thought that you meant before that you draw the raycast after the if statement
Yes
you need to draw after the raycast
that way we can tell if you hit anything or not
Like this?
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, pickupDistance))//, pickupLayer))
{
Debug.DrawRay(cam.transform.position, cam.transform.forward, Color.green); print("Hit");
Thank you so much! It doesnt solve the problem but im one step closer
no we would only be doing DrawRay when we missed, as mentioned already.
I'm seeing GC allocs from calling .Add() on a dictionary. Is that to be expected?
shouldn't be... can you show the code?
Usually you only need the LocalTransform component
What's the code to draw a line from the position to the landed raycast
Use DrawLine
and use the ray origin and the hit point
got it, thank you so much, ill look into it
Ah thats what I needed
Can anyone take a crack at what I need to do to fix these errors? They're stopping me from creating a build.
@leaden ice Ahh that looks so much better. It does seem to be colliding with my player, how can I work around that
I don't know anything about what you're doing or your game so IDK what that even means 😉
Are you using Visual Scripting?
Oh yeah 😆 third person game using C#
How do I make a raycast ignore a tag?
Is that what shader graphs use? if so yes
you make it ignore layers
no
shader graph is shader graph
visual scripting is different
If you're not using Visual Scripting just uninstall the package
Oh. let me double check
@leaden ice You life saving, cheers for the help!
I really should stop skimming errors 😛 Looks like that was the culprit, seems kind of random though. Thanks! Believe I meant to thank @leaden ice but thank you too
Trying to replicate to share a minimum reproducible, but having trouble getting it to recur out of context 😕
I've never really had this issue before, and to my knowledge I'm not doing anything unusual, but I am having a lot of my smaller rigidbodies falling straight through the floor. Any ideas how to fix this?
Like if you're doing something along the lines of
myDict.Add(key, new Someting());``` then it's the `new Something` with the GC alloc not the add
Also if/when the Dictionary resizes, it will allocate memory as well
I was thinking that could be the case. I'm creating a new struct - I thought structs didn't get GC Allocs?
structs stored in a dictionary are stored in the dictionary's internal arrays, which are in the heap
So this is relevant^
transform aspect was removed on the latest version of ECS
If you know ahead of time how many entries will be in the dictionary in advance it may be worth it to use the constructor with a capacity argument:
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.-ctor?view=net-8.0#system-collections-generic-dictionary-2-ctor(system-int32)
this will prevent unexpected allocations later on
at the expense of doing the allocation immediately
Is there some sort of recommended minimum size for rigidbodies?
Got it, that's very helpful. That did narrow down the root cause and I was able to replicate it by initializing a dictionary of a small size and forcing the resizing.
You'll see similar behavior with any of the dynamically sized collection types in C# including List, Queue, Stack, etc...
Is it typically better to define the maximum capacity ahead of time if known, even if it's likely that the full capacity will not be needed?
well if you don't use it all, it's wasted memory
but if resizing happens - that can take additional time when adding things, since you might need to reallocate and copy the data, and this also produces garbage (in the form of the previous, smaller array which is discarded) as you see
So - it's a tradeoff
OK, makes sense. And the Garbage Allocation only occurs when the dictionary is resized because it discards the previous dictionary (and allocates to clean up the corresponding references on the heap)?
well it allocates a new one, and leaves the old one for the Garbage Collector to clean up, yes
the allocation is what is caught in the profiler I believe
I understand now. Thanks so much for your help! 🙂
got a bit of a problem, I've got 2 layer one called "Ship" and the other called "MapView" I also have 2 cameras in the scene and i want each one to render one of the layers each. culling masks is the solutuion right? issue is when I hide "Ship" from the mapview camera it seems to stop rendering both layers
Culling mask settings:
Ship + MapView = everything rendered (intended)
Ship only = only ship rendered (intended)
MapView only = neither ship nor mapview rendered (unintended: mapview should be rendered)
Make sure the actual renderers are on the correct layers
Also this isn't a code issue
ah, my apologies, i'll move there
Quick question about some code, can I post an image to display it?
📃 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'm trying to use waypoints on a prefab because the prefab is being spawned but when it spawns it doesnt move?
you only seem to be setting target inside Move()
but Move() isn't called unless you're close to the target already
my VR game keeps freezing for half a second then unfreezing for 4 seconds then freezes etc... . I hear this is somewhat common and was wondering if there is a fix. It happened right after XR Origin.
Someone who's good at math, how would you calculate a direction that is perpendicular to another direction (or in other words, given the normal of a plane, find any direction that travels along said plain).
Vector3.ProjectOnPlane
its generally used to compress a 3D direction to some 2D direction
I'll look into that, thank you.
I recommend spending 60% of your time reading the documentation
Unity generally takes care of most things
I seriously need help
Yeah thx, I was scrolling up and down in the function list and for some reason missed it lol.
np
Is there a way to limit a UnityEvent to specific functions, and possibly pre-load a specific class?
Just to make the inspector more designer friendly
you can make it pre-load instances of components, but not really limit shown functions
it basically shows all public functions specific to that class
Yeah makes sense, figured there might of been a niche feature to do it. not a dealbreaker just would have been nice
How would I go about pre-loading a specific instance? in this case i just want it to be itself
let me check my claims
how?
depends on your editor version, check with google
I dont really know what a profiler is so Imma google that first
This is a simple code for running a smooth trail movement:
using UnityEngine;
public class SimpleTrail : MonoBehaviour
{
// Trail
private TrailRenderer Trail;
// Speed & Properties
public float MoveSpeed = 2.85f;
// Time
private float Duration = 0;
public float OperatingDuration = 4;
// Booleans
private bool IsDirectionPositive = true;
private void Update()
{
if (IsDirectionPositive)
{
if(Duration < OperatingDuration)
{
Duration += Time.deltaTime;
transform.Translate(transform.TransformDirection(transform.up) * MoveSpeed * Time.deltaTime);
}
else
{
Duration = 0;
IsDirectionPositive = false;
}
}
else
{
if (Duration < OperatingDuration)
{
Duration += Time.deltaTime;
transform.Translate(transform.TransformDirection(-transform.up) * MoveSpeed * Time.deltaTime);
}
else
{
Duration = 0;
IsDirectionPositive = true;
}
}
}
}
just put it on a the object that has the trail renderer
yeah I must've mistaken something, you can't set object instance
it seems like a profiler is where you can check performance, is that correct?
what you can do is write a custom editor I guess, that takes in a specific type in its definition like CustomEvent<Player>, maybe also add a function attribute to public functions that makes it seen to that editors dropdown
sorry not profile, read this
Hey guys, what's the new input system's equivalent to Input.getAxis("Mouse X") and mouse Y respectively? Using the Delta [Mouse] path seems to have a lot less precision than that
The delta will tell you how far from 0 the mouse moved that frame, is that what your looking for?
I think that's what I'm using right now:
This one just seems a lot more jittery because it uses discrete pixel values rather than some smooth function from -1 to 1..
aand I just realized I can probably divide it by the screen width and height to smooth it out
AFAIK, it just gives you the difference the mouse moved, so it likely would be much larger than -1 and 1, im not sure if dividing that difference by the screen resolution would give you a smoother value, though you can try it, or multiply it by deltaTime, or I think you should be able to add a processor to clamp or normalize the value, but depending on what your trying to do, you could just check if the difference is less than 0 or not
you can try Mouse.current.delta.ReadUnprocessedValue()
i think it is indeed just the delta binding
the new input system is so finicky
why my wheel collider and lines are not the correct manner ?
Seems to do the same thing as the Delta [Mouse] path in the input controller
what would the "correct" manner be?
my line should be on the that circles. but i dont know why it Maked like this.
when i use 4 tires they are place correctly
and how do you generate those lines? I assume the circles are the wheel colliders
oh wait i thought it created cuz of coliders.
i guess it's in the kit i use
anyone has any tips & tricks for integrating Epic Online Services SDK to a Unity game?
5 Sec google search... https://dev.epicgames.com/docs/epic-online-services/eos-get-started/eossdkc-sharp-getting-started?sessionInvalidated=true
google term "unity epic games sdk" ... not really a fact of experience 😄
ok sry i'm tilted because this is still a headache after days of trying 😄
Did you try that page already and have issues? Or did you just not find it?
yeah that's where I downloaded the SDK from 😛
am hoping more like.. tips on what libs/APIs to ignore, any actual code samples that made it work, or if I could use any shortcuts (e.g.: https://github.com/PlayEveryWare/eos_plugin_for_unity -- which seems kinda obsolete), etc
Why not just use that sdk with its tutorial dwon the page. They even made a Unity script example on how to use it. So maybe try to add this and come back when you are stuck 🙂
cool, thanks
my scroll rect is overflowing and putting a mask or rect mask 2d breaks the ui really badly. is there another way to hide the scroll rect behind other ui?
it'll work properly if you put a background behind it
leave the mask on, and just add a black image on a GameObject that's first in the UI canvas's hierarchy
it's on a panel and the panel i want it to render behind is not rendering on top of it
so the upper part definitely doesn't have a background
are yu sure you're not turning the main panel off while scrolling?
the issue you've shown would be caused if there is no background and camera doesn't clear. No other cases 😛
as in just an image behind it?
yup
seeing you don't have a camera in the scene, it definitely doesn't clear
adding a camera in the scene would also fix it, but you'd be left with the default Unity background -- likely something u don't want in UI apps
seems you're scrolling the container of the rect instead of the scroll rect content
I'd say create a default scroll rect and work from there without changing the references -- or check where the proper references go, and copy that to your Scroll Rect
yeah content shouldn't be the viewport -- Content var should be referencing the 'Content'
easy to mess up, lol
while you're at it, pump the scroll sensitivity up to 40 or 70. It's much better for in-editor testing
lmao.. no definitely not that.. Unity UI is a pain to get started with.. especially scroll rects and layout groups
Hey all, I recently openned an old project and I'm getting these annoying errors (Google and ChatGPT have been useless). I've deleted the library folder, made sure all my packages are up to date and I've tried on a different Unity version. Any ideas? 🙂
Backup your project and remove the library folder to let unity rebuild it. Seems like there might be some packages being cached and are not working anymore in your editor
I've already deleted the library folder*
I also did a "Re-import all" which I presume does about the same thing
Did you update your editor you are opening that project with?
yep! On the latest LTS first, then on the beta as a test
Than I guess you are just using packages which are not preview state any more. Didy ou check your packages?
yep
Maybe you have to look at your packages json file
You think the manager window would not show the update and I have to manually update it there?
Is there an easy way to know what the latest version for these are?
I think they are not even part anymore of packages and should be removed, but I am not sure, what was the original editor versino of your project?
I don't know :/ must have been about a year old :/
Ah okay, I think you can show hidden packages, one sec
Yeah there use to be an option in the little dot menu, but I can't find it anymore 🤔
Try to click advanced settings and Show dependencies, then reopen packagemanager and see if there is any update for you
alright I'll try tthat! unity is restarting...
I tried resetting to default and although it seems to help, it's also not really doable because it gets rid of all my custom packages I no longer even have in "my assets". So I rolled back on git
Also, I don't see "advanced project settings" but here's the "project settings" windows. I don't see anything about "show dependencies"
I think you're onto something with editing the manifest manually. But I'm not sure where to find the right version for every package :/
(thank you for your help btw 🙏 )
How does your package-lock json look like?
I'll send it to you asap, I tried reseting the packages again but this seems to not just reset to default but entirely remove ALL packages ^^' including unity built in ones...
so this is what I see right now ...
I'll rollback once more and give you the lock file! 1 sec
It looks normal to me, would you like me to share the file here?
I can tell you, that there is no single platform entry on my current project for example
I want to graphics.copy from rendertexture to texture2D, they are both RGB565 with mip maps off and same resolutiob, but it throws mismatch error
what type is texture and the other one?
source is Render Texture RGB565 with resolution 32x32 and mip mapping off, dest is Texture2D RGB565 with resolution 32x32 and mip mapping off
You might have to convert your rendertexture to a base texture, because texture2d and rendertexure are both different inheritance from texture itself
I have this error in console which points to this line where I set DontDestroyOnLoad to elements in a list referenced in the inspector.
When debugging in visual studio, I don't have any error on these lines and it goes through the rest of the code fine.
It doesn't seem to cause any issue, but I still wonder why it shows up?
Are you trying to dontdestroyonload items from your project folder structure?
no, gameobjects in the same opened scene as this script
Sorry had to go, I'll try deleting these entries then! Cheers!
Is there a way to have 1 ParticleSystem to spawn particles in different places?
For example I move it to position X. Spawn particles. Then move it to position Y and spawn particles. So that previous particles stay intact in previous spot.
Does reopening Unity change anything?
How can I get the lowest value from a List<int> using a lambda expression?
List.IndexOf + List.Min()
Great. Thank you 🙏
i would guess spawning the particles in worldspace?
not sure if they then get detached
thinking of it, yes it works, doing exactly that
Absolutely, always takes some time before I think of rebooting Unity, but it works so often 😅
No problem, always try a restart with these internal errors 😄
Does List.IndexOf(value) get the first element in the list with the value value?
Yes
Otherwise use LastIndexOf
You can overload IndexOf with arguments if you want a different occurance
Such as list.IndexOf(2, list.IndexOf(2) + 1); to get the second 2 in the list.
wondering does anyone know how the constructor for Color works? is it the same as a simple Vector4 or does it do something special to it? (it would take too long to explain why this matters...)
Hello i am trying to use a line renderer it has been working completely fine before i set up a post processing unit and now i can see its still there but it is invisible does anyone know how to fix this?
Is anyone able to help me with this? https://answers.unity.com/questions/1943642/ruletile-rotation-of-gameobjects-on-xzy-tilemapgam.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I have a tilemap that by default has the wrong rotation for gameobjects
does anyone know why some of my stuff is disappearing while im in scene view?
I've had this issue before! It seems to be triggered from zooming in and out too many times! Somewhere in scene view should be something to help you fix it, although I can't remember where sorry...
ah alright thanks i'll have a look
wish ya luck!
tyty
Is there any lib/plugin that adds some sort of ingame console to a unity app?
That can be opened and viewed to see logs n stuff?
fixed it by pressing ctrl f on an object and that seems to reset the zoom
is there a way to draw 2d spline maps instead of having to customize it with a sprite and dragging all the dots around
good job!
It’s just F
Also, this is a channel for questions about code
probably the editors camera near plane.
cameras stop rendering things if they are closer than that "imaginary" plane
not sure how to change that, noticed similar things
how can i join these together
there it is
seems that dymamic clipping gets confused
right click, add empty parent
where is it
ah thank you
when you use the animation rigging package can you mix procedurally generated animations with traditional animations ?
Is this valid code? ```cs
public PlayerState state;
public enum PlayerState
{
Moving,
Falling,
Idle
}
// Start is called before the first frame update
void Start()
{
int playerState = (int)state;
}```
If state == PlayerState.Moving I want playerState to be 0
If state == PlayerState.Idle, I want playerState to be 2.
And what does state.ToString() do? Will it say Movingor PlayerState.Moving?
public class LevelButton : MonoBehaviour {
private void Start() {
button.enabled = false;
text.text = "";
if (Mathf.Clamp(PlayerPrefs.GetInt("CompletedLevel", 0) + 1, 1, levelsCollection.levels.Length)
>= representedLevel)
{
text.text = representedLevel.ToString();
image.sprite = newSprite;
button.enabled = true;
button.onClick.AddListener(() => {
LevelsCollection.currentLevel = representedLevel;
});
changeSceneButton.SetSceneToLoad(levelsCollection.levels[representedLevel - 1]);
}
}
}
public class ChangeSceneButton : MonoBehaviour {
[SerializeField] public UnityEngine.Object SceneToLoad;
[SerializeField, HideInInspector] private string str;
private void OnValidate() {
str = SceneToLoad.name;
}
public void SetSceneToLoad(UnityEngine.Object SceneToLoad) {
this.SceneToLoad = SceneToLoad;
OnValidate();
}
public void LoadScene() { //called from click on UI Button
SceneManager.LoadScene(str);
}
}```
I have this code which sets which scene to load with my button. It works fine on my PC but always loads the first level on my phone(
Any ideas how to fix it?
I am not really sure, but PlayerPrefs.GetInt("CompletedLevel", 0) seems like a terrible idea for save.
And, it seems like you actually need to call PlayerPrefs.Save() to propagate the change. https://docs.unity3d.com/ScriptReference/PlayerPrefs.Save.html
So, maybe you are not doing it ?
Ohhhhh wait
And, did you include the scene in the actual build ? https://docs.unity3d.com/Manual/BuildSettings.html
i wouldnt cast enums to integers, if its not absolutely necessary.
the whole reason for enums to exist is that integers are hard to read and messy
with enums, switch is your friend
switch (state) {
case PlayerState.Moving:
playerState = PlayerState.Owo
breaK;
default:
throw new UwuException();
}
I guess. But then I need to manually convert it to an integer
Because I need it to pick an element in a list
public Transform[] abilityObjs;
public void AbilityButtonUpdate(Ability.AbilityType _type)
{
abilityObjs[(int)_type].gameObject.SetActive(true);
}```
Essentially
you could use a dictionary instead that maps AbilityType to object.
But why?
That's just a bigger mess
because as soon as you reorder your ability enum, f.e. by adding a new state in the zero place, your array breaks
What component do I have to add to my entities to make them fall using gravity
your code works, but its not safe to changes
Yeah. But I won't. This way I can easily assign the Transforms in the inspector, which isn't as easy with Dictionaries
rigidbody
cant use rigidbody on entities
Great. Thank you
then code the gravity i guess
yeah I guess thats the plan then, I actually needed everything but I think Ill have to use another physics system
Hello, i have a problem:
{
SpriteRenderer[] spriteRenderer;
void Start()
{
spriteRenderer[0] = GetComponent<SpriteRenderer>();
spriteRenderer[1] = GetComponentInChildren<SpriteRenderer>();
}
void FixedUpdate()
{
float screenHeightInWorldUnits = Camera.main.orthographicSize * 2f;
float scaleFactorY = screenHeightInWorldUnits / spriteRenderer[0].sprite.bounds.size.y; // THIS IS LINE 18
spriteRenderer[0].transform.localScale = new Vector3(scaleFactorY, scaleFactorY, 1f);
float screenWidthInWorldUnits = Camera.main.orthographicSize * 2f;
float scaleFactorX = screenHeightInWorldUnits / spriteRenderer[1].sprite.bounds.size.x;
spriteRenderer[1].transform.localScale = new Vector3(scaleFactorX, scaleFactorX, 1f);
}
}
So, if i run this code, it will say:
NullReferenceException: Object reference not set to an instance of an object
ScreenAutoFit.FixedUpdate () (at Assets/ScreenAutoFit.cs:18)
(Line marked on code)
I cant understand, i even put the lines from start together with fixedupdate and still doesnt work
Do you have a camera with the MainCamera tag?
Read the error
havent touched the camera so it must have the tag
yup
Check
it haves
What would be a good way to have a nav mesh agent calculate a path to walk around other agents? I want to keep my enemies spread out further from one another rather than bunching up. I can increase the avoidance radius, but that just makes the agent that is in motion push the other agents out of the way rather than having the agent walk around the other agents.
Figure out what's null
i tested by putting the spriteRenderer to debug log and i got it on that debug line
It has no sprite
Or the array itself is null
this is the object thats linked to the variable
Because you never initialize the array
You never initialized your array
It's null
And you're getting an error in Start too
i've intialized on start
No you didn't
You would need spriteRenderer = new SpriteRenderer[2]; for example
Right now your array is just null
you meant this one?
Also both of those GetComponent lines will return the same object
Arrays are objects themselves yes
i have as children an object with spriterenderer component
wait
Doesn't matter
GetComponentInChildren checks the object itself first
what
You'd do transform.GetChild(0).GetComponent
oh
Or just assign it in the inspector which is better
Hey guys, how can I out an empty raycast in case my function did not hit anything so my code won't throw a null reference exception?
I can't even let the out variable empty, so there has to be some value in it and I can't come up with an idea 😕
private bool CastSelf(Vector3 pos, Quaternion rot, Vector3 dir, float dist, out RaycastHit hit)
{
// Get Player Capsule params
Vector3 center = rot * _playerCapsule.center + pos;
float radius = _playerCapsule.radius;
float height = _playerCapsule.height;
// Get top and bottom of Player Capsule collider
Vector3 bottom = center + rot * Vector3.down * (height / 2 - radius);
Vector3 top = center + rot * Vector3.up * (height / 2 - radius);
// Check for hits in given direction and distance, return nearest object as RaycastHit if possible
if(Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, _tempHits, dist, ~0, QueryTriggerInteraction.Ignore) > 0)
{
IEnumerable<RaycastHit> hits;
hits = _tempHits.Where(hit => hit.collider != transform);
float closestDistNonAlloc = Enumerable.Min(hits.Select(hit => hit.distance));
IEnumerable<RaycastHit> closestHitNonAlloc = hits.Where(hit => hit.distance == closestDistNonAlloc);
hit = closestHitNonAlloc.FirstOrDefault();
return true;
}
else
{
hit = _tempHits.FirstOrDefault(); // << Can't be empty, still gives error like this
return false;
}
}
this was the solution
Usually you just do hit = default; when there's no hit
OK, that's easy, convenient and I was not aware of this 😄
Works, 2 hours wasted - Thanks 😄
2 hours, that's amateur number
Will try harder next time 😉
We pick implementation strategies on likely number of hours wasted
is there a way to duplicate only the mesh renderer parts of an object?
as right now im instantiating an object and then destroying each script component afterwards
however that is causing errors with both awake methods and scripts that depend on eachother
so im wondering if theres a way to skip the destroy part and only spawn the necessary rendering components upon instantiate
Create an empty object and add a mesh renderer and mesh filter, copy over the materials and mesh
i will try that, thank you
Again maybe a n00b question, but I've added a Layermask to my Raycast to ignore the Player, which itself and all childrens were assigned to - but I'm still getting hits from it
Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.NameToLayer("Player"), QueryTriggerInteraction.Ignore)
Any idea?
NameToLayer is not how you make a layermask
LayerMask.GetMask
Well, works again, kinda got the Docs wrong
Anybody got any advice for custom tiles. Say I wanted the player to place a tile, for example a factory tile. Which has a coroutine which basically just does something every X seconds.
So I create a custom tile, but there is no method 'OnTilePlace' or something like that which I can override to start a corouitine? Any ideas?
Is the only option to add the method to the tile and call the method when it gets placed?
example code:
tilemap.SetTile(tile)
tile.StartTimer()
You could create a class that wraps the TileMap that can be use to include events.
public class MyOwnTileMap : MonoBehaviour {
[SerializeField] private TileMap tileMap = null;
public event System.Action<...> OnTilePlaced;
public void SetTile(...) {
OnTilePlaced?.Invoke(...);
tileMap.SetTile(...);
}
}
Alternatively, you could try to implement your own tile and trigger an event whenever the tile is created. However, beware to not use the Tilemap as a way to store/update your tile. You should try to limit your usage of the tilemap to render function exclusively.
https://docs.unity3d.com/ScriptReference/Tilemaps.TileBase.html
what do you mean
🤔 Asking Questions is very useful for you
yes
How do you reference a game object's script? I have a script attached to an otherwise empty game object called "Logic" and the below code is trying to reference that code so I can use its methods. But I'm hit with an "object reference not set to an instance of an object" error.
{
Logic l;
Color pickupColor;
SpriteRenderer driverSprite;
// Start is called before the first frame update
void Start()
{
l = GameObject.FindGameObjectWithTag("Logic").GetComponent<Logic>();
}```
The object is in the scene, so I know it's not an issue of there not being an instance of it.
Also, feel free to point out the other dozen things wrong about that short snippet of code if you'd like. I feel like I'm doing everything wrong.
If you're getting an NRE with this code then FindGameObjectWithTag("Logic") is returning null, meaning no active object with that tag was found.
Is there a good reason you aren't just assigning your reference in the inspector?
@naive swallow can you use your macro please thanks
Which one I have a lot
On referencing objects
A few basic ways to get references in Unity.
Directly-
GetComponent 0:38
/GetComponentInChildren
/GetComponentInParent
Public Variable- 3:00
Find- 5:01
Find 5:39 (by name)
FindWithTag 6:14 (by tag)
FindObjectOfType 6:51 (by component)
Interaction- 7:15
OnCollisionEnter
/OnTriggerEnter
I guess I just prefer trying to do everything via code.
@lunar forum ☝️
I'm writing a grid system but I have a mathematic problem with getting the node from a world position. I basically wanna snap to the node as soon as the target is inside the square around the node (the unity grid is representing the square i mean). However as you can see in the video this is not working right now.
public Node NodeFromWorldPoint(Vector3 worldPosition) {
float percentX = (worldPosition.x + (width / 2f)) / width;
float percentY = (worldPosition.z + (height / 2f)) / height;
percentX = Mathf.Clamp01(percentX);
percentY = Mathf.Clamp01(percentY);
int x = Mathf.RoundToInt((width - 1) * percentX);
int y = Mathf.RoundToInt((height - 1) * percentY);
return nodes[x, y];
}
public void CreateGrid()
{
nodes = new Node[width, height];
var name = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Vector3 startPosition = new Vector3((width) / 2, 0, (height) / 2) - new Vector3(0.5f, 0, 0.5f);
Vector3 worldPosition = (transform.position - startPosition) + new Vector3(x, 0, y);
nodes[x, y] = new Node(true, worldPosition, x, y);
if (visualizeNodes) {
nodes[x, y].createInstance(nodeInstance);
}
name++;
}
}
}
How would I tackle this issue? What mathematical mistake have I made?
Can anyone suggest me how many programming patterns i should know for developing hyper casual games fast
this is a very vague q that doesn't really have an answer. what do you consider "hyper casual"? how big are these games? how fast are you expecting to develop these games?
in any case, understanding programming patterns doesn't really yield a faster rate of production. it'll just make your code more structured and maintainable.
My playerobject is destroyed when it sits on the floor, it has a bouncy rigidbody, which might be the cause. How do I fix this?
Nice!! Thanks! Thanks a great way of doing it, I wouldn't have thought of that. And thanks for the tip about not using it too much 🙂
hey everyone, I want to create a save system and for that i'd need each object to have a unique, permanent ID. However I can't find anything that allows this (GetInstanceID is not permanent so it won't work) does anyone has an idea on how to create a permanent ID system or is there already something like that in Unity ?
Guids?
They won't be the same on every system though
You could use an editor script to automatically assign a guid to every gameobject, that way it would be the same for everyone
ok thanks a lot !
thats not a problem

Do you need a unique id because you need to ensure that the saved data is returned to where it was saved from, or just saving in general?
If saving in general, either an unique guid using Guid.NewGuid() or you can use a regular int. For the latter you should check what the last int was that was saved, which is more work.
If you need to keep track of the class that saved it, why not get the full name of the class? typeof(yourClass).FullName
I need a unique ID for each object that needs to save data
thats why i want each object to have a unique and permanent ID
Quick question trying to get the transform of waypoints and convert it to a vector3 for the NavMeshAgent. I did Debug.Log and it shows its getting the waypoints but its not moving?
Yes, decimal.parse takes a string and converts it to a decimal, but Math.PI * 2 is already decimal
If anyone could take a look at my forum post and help me out that'd be fantastic also
Can anyone link me to script to save runtime instantiated meshes/prefabs into assets?
This is the only thing I found but it doesn't seem to work for me.. (does not show in editor)
https://forum.unity.com/threads/solution-save-a-prefab-with-a-generated-mesh-es-without-creating-assets.463496/
bc you keep setting the agent destination to target at the start of every frame, then you use MoveTowards to set its destination (not sure why as this is the destination or end position for the unity to move to) when it's not yet at its current waypoint. the agent moves on is own . . .
Anyone know what could be causing this jittering? I only have a Character controller script in the scene.
are you using FixedUpdate?
an idea ? I searched on the internet but no topic about this prblm on unity and the available topics was about js and webAPI permissions in short nothing to do I really don't know where it can come from, I tried on the beta 2023 of the software and there on 2022.2.12 both times with HDRP and same problem for both versions :/ thanks for any help!
Horizontal rotation and headbob are on update. vertical rotation is on late update
are you lerping the camera?
only for the headbob
try disbaling the headbob is it still jittering?
I'm not sure how you implemented the headbob, but I have a suspicion it is causing the jitter
Otherwise, remove one part of your movement script at a time and test that the functionality is indeed working without jitter
(Test only Horizonal rotation, then only Vertical rotation, then Only Headbob, then start combining variations of these systems together until you find the culprit)
I have a list that I am trying to populate from the Inspector, however I think I'm missing something
[Serializable]
public class CharacterStat{ //does base functions
}
[Serializable]
public class HealthStat : CharacterStat
{
//Does health specific things
}
[Serializable]
public class MovementSpeedStat : CharacterStat
{
//Does movement speed things
}
This is my parent child set up for stats to inherit functions but also manage their own specific stuff. I'm struggling to be able to add these individual classes to a list
[SerializeReference] public List<CharacterStat> statList;
What am I missing here?
Does it help if you initialize it?cs [SerializeReference] public List<CharacterStat> statList = new List<CharacterStat>();
Just wondering if that matters when using SerializeReference
That's what I've been doing, though my List's <T> has been an abstract class or interface
oh let me try I thought about doing that but never ended up testing
Its also initialized in the doc examples so that might be it
hmm still no dice, I'd imagine its someweird inspector thing because they are just classes and not monobehaviors? i dont know :c
The doc also says that SerializeReference should not be used for UnityEngine.Objects (which MB are) so thats not the issue
What if you make a new list variable just to test? And give it an initial value
Are you sure that CharacterStat does not inherit from any UnityEngine.Object class?
are you sure you want to use SerializeReference there?
how to fix this
Is there any way to story json data in application memory instead of file memory?
For Android build
Check the class name and file name
They should be same
Do as the dialog instructs
Do what it says
??
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
I'm getting confused with what should be a pretty simple raycast. if(Physics.Raycast(ray, out hit, rayLength, LayerMask.GetMask("Lightsaber"))), it correctly only hits objects that are on the "Lightsaber" layer, but the object returned by hit.transform is the object's parent.
Don't use chatbots
Do beginner scripting tutorials first
im not using that
when i cant understand something i just ask them questions
but this time bot cant help
Well don't do that, the bot gives you false advice which you can't spot with your level of knowledge
Use real guides and tutorials instead
The problem with your script was already explained to you in code-beginner, so the next step is to look at beginner scripting tutorials to see how it works in practice
Or google the error for forum threads with more instructions
do you perhaps have errors in your console such as errors suggesting you are missing a using directive?
okay
your class name doesn't match the file name
Don't cross-post, stay in #💻┃code-beginner where you originally asked . . .
sorry
An answer was provided for you there . . .
ok i wont
Any ideas?
i'm guessing the parent object has a rigidbody on it?
hit.collider will reliably give you the actual object you hit
Oh, thank you. I thought it returned the collider instead of the rigidbody
if you want the collider use hit.collider then you can grab the transform from that. since it's a child of a rigidbody it becomes part of a compound collider which means some properties for the raycast hit will point to the rigidbody object
Yeah, I'm using hit.collider now thanks.
So, i've been working on implementing this way of doing it, but still getting the same error.
Hey all, I want to create an enemy that has a sphere (or circle, since it's 2D) of influence that increases a certain stat of the players when inside it. Right now I have it set up with an empty child on the enemy, a sphere collider on said child and a OnTriggerStay2D that executes the code. Then, I made sure that the physics from the player's hitbox wouldn't affect the trigger because the player could hit the enemy through the trigger lol.
It works as intended, but I just get the feeling that changing the physics collisions seems kinda messy and not very good praxis, so I was wondering if any of you would have done it/would do it differently.
And while I'm at it, Id also like to ask what you guys would think is the best way to check if the enemy is facing away from the player or not (I would like to implement a backstab feature)
hey um
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
public class trow : MonoBehaviour
{
public SpriteRenderer sword;
public Rigidbody2D rb;
private float dirX = 0f;
[SerializeField] private float moveSpeed = 7f;
public Rigidbody2D rb2;
public Transform transform;
void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
if (Input.GetKeyDown(KeyCode.T) && sword.enabled == true);
{
rb.velocity = new Vector2(dirX + moveSpeed, rb2.velocity.y);
if (transform.localScale == new Vector3(-1, 1, 1))
{
rb.velocity = new Vector2(dirX - moveSpeed, rb2.velocity.y);
}
;
}
}
}```
here
when i press t and sword is on
i want to shoot it
shooting is working
something simmilar
but
when i spawn in game
; ending your if statement early
make sure your !IDE is configured so it shows warnings about things like that
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.
it does it immediately
then you should have seen the warning about a possibly empty if statement
well if you've removed that ; then it shouldn't unless there's some other context you aren't providing
ok
imma fix that later
but now uh
look at this
there is missing ;
at if sentance
when i fix it
it doesnt work the way i want
when i dont
it works way i want
like
it works so what sword shoots at way im looking
if i dont fix it
if i do it just goes to 1 direction
to the right
you still have the extra ; on your if statement. it's literally right next to your cursor. remove it
this?
yes
okay
its all broken now
it doent move if i wont move
and skips sliding part
just teleports to where it would have been if i moved
So I'm trying to refactor in order to have my unit data in a scriptableobject separate from the unit controller - the unit data contains the unique variables and logic for different units (different class for each one), and is executed by the controller (which is generic). Is that dumb?
Okay so you don't need to add the {} to use the if statement
That's why the ; is valid syntax
Watch
in your case you do
good
if (X > y)
doSomething();
Is the same as
if(X>y)
{
doSomething();
}
you can exclude the braces only when there is a single statement in the scope of the if statement
OOOH
maybe it's dumb because the data will need to refer to variables in the controller (because those might be different due to in game effects)?
i didnt knew that
However the first approach only works with a single statement
thanks for telling me
And is prone to errors
also you should consider asking questions in #💻┃code-beginner moving forward. especially if you don't know basic c# syntax
So you should always use {}
and just having a ; is a empty line
So nothing will be done on that line
thus having an if followed by a ; is just and if this then do nothing
thanks a lot! i understand now
if (X > y);
Is the same as
if(X>y)
{
;
}
Are you just not supposed to put logic inside scriptableobjects?
you can. but a lot of people will recommend against it and recommend using scriptable objects only for immutable data
So if you have units with potentially unique variables and methods, you might as well just not bother with SO?
As in, an SO won't be sufficient to describe the unit
you can, that's perfectly fine. but if you need to access those unique variables and methods but you've stored the reference to the SO as its base class you'd need to downcast to the correct type to access them
You can also convert a scriptablw object to a runtime object, so if a entity can shoot add an enum that it can shoot or melee and then at runtime check which ome is set when instantiating it
In this case I would need to have a separate set of variables on the instance controller since those can be changed by in game effects (while you wouldn't want to change the base data). So then you'd be using the instance for both logic and variables so... does the SO serve any purpose at that point?
Could you give an example?
If you are building your things in runtime anyway SOs don't make any sense to me atleast
Well every time I try to use SOs they end up just not making sense to me
I guess it's just for simple data and that's it
Also that static switch case example seems just bad
I'll just give up on SO for now
Can build a system using reflection to get behaviours bound to enums
Don't need a switch case
I'm trying to implement a timer that kicks off some methods. I can't use a traditional deltaTime timer (afaik) because this timer is happening inside of an event listener. My solution was to use a simple coroutine with a waitforseconds, but that doesn't seem to be working how I thought it would
void OnStartNewRound()
{
//some other things
StartCoroutine(KickoffTimer(timeToWait));
//the rest of the setup
}
IEnumerator KickoffTimer(float timeToWait)
{
yield return new WaitForSeconds(timeToWait);
}
any input as to what I'm doing wrong here?
a coroutine will not delay the method it is called from, it can only delay itself (or technically it could delay another coroutine if the startcoroutine call is yielded in that outer coroutine)
put everything you need to do inside the coroutine and have OnStartNewRound call the coroutine, or subscribe to whatever event with a lambda that just starts the coroutine
gotcha. Thanks
Hi guys, got a bit weird behaviour with sorting an array that sometimes only has one item.
int hitLength = Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
if(hitLength > 0)
{
for(int i=0; i < hitLength; i++)
{
Debug.Log("Hitlength:"+hitLength + " Hit"+i+": " + hitArray[i].normal + " name: " + hitArray[i].collider.name);
}
// Sort array by distance
Array.Sort(hitArray,(x,y) => x.distance.CompareTo(y.distance));
hit = hitArray.First();
Debug.Log("Hit return: " + hit.normal);
return true;
}
By sorting like this I'm getting a normal of (0,0,0) all the time, despite for-loop showing the real normal and a hitLength of just 1.
Commenting sort out returns the same normal
why are you doing hitArray.First() instead of hitArray[0]?
Anyway you can't really do Array.Sort here
because the array is going to be longer than the actual number of hit results
You're better off using the List version of CapsuleCastNonAlloc here
Found I can do this 🙂
int hitLength = Physics.CapsuleCastNonAlloc( top, bottom, radius, dir, hitArray, dist, ~LayerMask.GetMask("Player"), QueryTriggerInteraction.Ignore);
if(hitLength > 0)
{
for(int i=0; i < hitLength; i++)
{
Debug.Log("Hitlength:"+hitLength + " Hit"+i+": " + hitArray[i].normal + " name: " + hitArray[i].collider.name);
}
// Create comparer to allow comparison of RaycastHit Type
Comparer<RaycastHit> comparer = Comparer<RaycastHit>.Create((x,y) => x.distance.CompareTo(y.distance));
Array.Sort(hitArray,0, hitLength, comparer);
// float closestDistNonAlloc = Enumerable.Min(hits.Select(hit => hit.distance));
hit = hitArray.First();
int index = 0;
foreach(RaycastHit rchit in hitArray)
{
Debug.Log("Hitlength:"+hitLength + " Hit"+index+": " + rchit.normal );
index++;
}
return true;
}
And reset Array before
I didn't realize Sort has that overload
that's perfect for your use case
still
hitArray[0] will be faster than hitArray.First();
Sure, will change that 🙂
Took me a bit of crawling through Array.cs to find this but it's easy to use and I guess way faster than dealing with lists
Could do a lil bit of optimization by not creating a comparer every time the function is called
hello
hi, I've locked my mouse in position with Cursor.lockState = CursorLockMode.Locked;, and then I gather user input through
float mouseX = Input.GetAxisRaw("Mouse X") * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensY;
but, on my reset function I need the mouse to return back so both Input.GetAxisRaw("Mouse X") and Input.GetAxisRaw("Mouse Y") return 0. Is this possible?
Input.GetAxisRaw should only be the delta this frame.
The mouse should still be at center and not moving.
Maybe just set mouseX and mouseY to zero if you're wanting to default the values to zero in some function.
sorry I’m new to unity and C#, what is a delta? and I use the input.getrawaxis in my update function. I’m making a new function that can reset the position of the player, I can easily move them but when I try to rotate them the function I have for turning just immediately puts them back to their previous position due to the Input.GetAxisRaw not resetting as well and so the game keeps them looking in that direction. I hope that makes sense, please correct me if I’m wrong
a delta is the change in value from the previous frame to the current frame . . .
delta means change in, so in this context, the delta is the space you moved your mouse on the x and y between the previous frame to this frame
ah okay that makes sense, thank you all
I’m not really sure what your issue is though something to do with rotation?
I will do my best to explain but if it’s unclear then don’t worry about trying to make sense of it
so my cursor is locked and the player can move the mouse left and right to turn left and right, and as it is just a first person character I just rotate the camera that is inside the players rigid body, and all works fine. When I try to teleport the player to a location it also works perfectly fine, but when I try to teleport them and rotate them so they’re facing a specific direction, then problems arise. I tried many methods to rotate the player, such as transform.eulerAngles, Quaternions, all that sort of stuff, and the player would rotate but then instantly be rotated back to their original direction. I presume this was because the program still thinks the mouse is in a place which links to a specific direction to face in, but I’m not sure. I’ve tried changing stuff but it hasn’t really worked, and so I came here for help
how are you using mouseX?
like the rotation code
that’s to look up and down
could you send the code
ideally pastebin
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.
^ that is my code for the generic turning of the camera
all you need to do is set xRotation and yRotation to match the new euler angles you want
wow, it was that simple
i kid you not i spent like 3 hours trying to figure out a solution 😂
rotation can be tricky
well, thank you very much for that!
no problem
I can think of some janky ways to forward the calls but is there a decent way to get ontrigger function calls on behalf of another object?
sure, just pass the data along