#archived-code-general
1 messages ยท Page 151 of 1
Unity made that weird decision
i feel its the better decision, due to my reason above your message
strange.
damnit my message had a typo, corrected
that should only really happens on numbers that cannot be represented properly
I see
ok, System.Sign then
what's that for?
hhmm... I am realizing I need some way to handle tracking "Activated" entities, which are ones only within lets say 2 screens of the player, best to ignore any entities out of "Range" and they stop doing stuff and mattering for calcs
Hello, I would like to know how to use more than one extra thread when using system.threading and async/await funcitons. I know that you can use async/await and tasks to run code on a seperate thread but I don't know how to use more than one seperate thread.
Do you have a use case for this?
You might want to take a look at the C# Jobs system, part of the Unity DOTS package.
Im using many references in my code so I can't use the jobs system
its a procedural world generation system
Right.
Have you tried the native Threading library?
that's what im tryna figure out atm
Maybe it's worth it to convert your system so it doesn't use references so you can use the Jobs system.
Look into UniTask
async functions called from the Unity main thread don't run on a separate thread, you can use await Task.Run(() => ...stuff here runs on a worker thread...)) but it sounds like you might want to check out Parallel.ForEach for your case
private void SaveCurrentData()
{
var str = JsonUtility.ToJson(temp, true);
TextAsset textAsset = new TextAsset(str);
AssetDatabase.CreateAsset(textAsset, $"{relativePath}/Level {temp.levelNumber}.asset");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
``` so i make Text Asset via Code, and its work. the text are created on correct path, but i though i can open it from Vs Code, then when i click that text asset, nothing happened??, why??, does unity Text Asset can't be open?
yea thats what I used\
What do you mean "nothing happened"? What were you expecting to happen?
Hey, I'm having problems when changing resolution. Should I set all UI elements with anchors only and never use size?
This is a coding channel #๐โfind-a-channel
To manage a project, suppose there are some columns like TODO, InProgress and Done. If you prefer to add QA and Review columns, how do you estimate sprint point or hour for that task? Consider all from TODO state to Done with QA + Review?
Not sure if this is the right channel for this but for 2-week sprints, our pointing system is: Less Than Half Day, Half Day, 1 Day, 3 Days, 5 Days (1 week), 8 Days, 10 Days (2 weeks). This does get the ticket from TODO to QA in the same sprint but usually not closed until the next sprint.
OK, thanks and what if different person should handle QA and Review.
Change the assignee or create different cards
It's still the same because they are blocked until work on the ticket has been done. Usually, QA will test the tickets that were sent to them in the previous sprint. But if there are enough people, QA can test within the same sprint.
Just change the assignee
Usually we create new ticket if we re-scope the ticket
So time estimation should include both dev + qa
Definitely. Sometimes we also do Bugfix-only sprints where no new features are allowed.
It is a bit confused how much it is for dev and how much for qa if just one card has been created
Since QA is often blocked until the engineers finish the feature, it doesn't make sense to create a separate ticket for them. We just reuse the same feature ticket and make sure it fulfills all the acceptance criteria.
Because if they have their own ticket, the ticket will remain blocked until the feature is ready for QA anyway.
So just use the same ticket and pass it around. Less tickets to manage.
OK, thanks so I estimate time dev + qa together, double it
Hello, I have just started making a 2D game with new Input System.
I already have a movement, where coroutine is started in InputAction.started and the player is moved every moveDelay seconds by moveUnit.
He's moved with just 1 axis: (1, 0), (-1, 0), (0, 1), (0, -1).
I want to do it so that when move Vector is changed from (1, 0) to e.g. (1, -1) -> player starts moving to the new axis that is in our case (0, -1) (-1 is KeyCode.A).
(1, 0) -> (1, 1) = (0, 1)
0, -1 -> 1, -1 = 1, 0
Any ideas?
note: that's not just #๐ฑ๏ธโinput-system topic, that's why I ask in #archived-code-general
Set a variable that is read from the coroutine
what do you mean, everything is performed within coroutine
Or cancel the coroutine and start a new one
Create a class scoped var, store direction in there
Read said var in the coroutine to determine direction
I have tried to use prevDirection, but I haven't succeded
Coroutines are just functions
Coroutine doesn't seem like a good choice here. Just read the input data in Update
I have a delay
Use a timer variable
Delays in coroutines aren't consistent anyway
Of course
making it in Update doesn't seem to solve anything
Counter or timer in fixed update is probably better if it's some thing the player has control over
If just background scenery and you don't care about consistency then use update or coroutines
yeah, doesn't seem like I can achieve that movement by just making it in update or fixedupdate
Your problem is that you don't know for to store the last direction though
This
there are 2 last directions, do I store both?
yes, 2 Vector2s
Yeah why not
and one new
Do you care about the old?
yes, if I just check one prevDir, then the movement is zig-zag
(1, 0) -> (1, 1) = (0, 1)
void MoveOnce(out bool canContinue)
{
Vector3 dir = callback.ReadValue<Vector2>();
dir.x = Math.Sign(dir.x);
dir.y = Math.Sign(dir.y);
Vector3 defaultDir = dir;
print($"dir default: {dir}");
if (dir.x != 0 && dir.y != 0)
{
if (dir.x != prevDir.x)
{
dir.y = 0;
}
else if (dir.y != prevDir.y)
{
dir.x = 0;
}
}
print($"prevDir: {prevDir}; dir: {dir};");
Vector3 newPos = transform.position + dir * moveUnit;
if (!_gameFieldBounds.Contains(new Vector2(newPos.x, newPos.y)))
{
canContinue = false;
return;
}
canContinue = true;
prevDir = defaultDir;
transform.position = newPos;
}
Looks good to me
it doesn't actually
it's zig-zag
wait, why does it have (1, -1) vector...
actually I also wonder if I can achieve this by doing smth in input-system..
I think I gonna try to achieve this behaviour a bit later
I don't know what you are doing and what you are trying to achieve
hello! i have two objects, and im trying to make it when i hit one of them with bullets they flash white, and i've managed to do it with sprite masking, however when they are near eachother i find that the flash is shown on each object with the mask, nmot just the parent ofitself
i can't find anything online that mentions one object's mask stuff showing on another
Anyone know why I cant reassign vertices?
I am drawing a map of hexes, originally, I had 600 vertices. I then removed 1 hex, thus, now my vertices array on the left has 594 vertices.
I am trying to reassign it to the mesh, but the mesh.vertices wont update and still has an array count of 600
anyone know why?
If this is a visual only feature, perhaps you could use a shader to change the colors
you could also just change the color of the sprite to white
To make changes to the vertices it is important to copy the vertices from the Mesh. Once the vertices have been copied and changed the vertices can be reassigned back to the Mesh.
I've used the API in the past and I had no issue.
Maybe you did not invoke mesh.vertices before ?
Also, is your mesh ReadWrite ?
yea, I can RW
I mean, does it have the option enable.
Debug.Log would be your friend here
To ensure the lengths of things are as you expect
just verified, is readable to true
i've had lots of bad experiences with shaders :') i looked around online and saw that for 2d masks can be easier
Follow the tutorial and see if it works.
using UnityEngine;
public class Example : MonoBehaviour
{
Mesh mesh;
Vector3[] vertices;
void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
vertices = mesh.vertices;
}
void Update()
{
for (var i = 0; i < vertices.Length; i++)
{
vertices[i] += Vector3.up * Time.deltaTime;
}
// assign the local vertices array into the vertices array of the Mesh.
mesh.vertices = vertices;
mesh.RecalculateBounds();
}
}
Im using breakpoints in Visual studio, let me verify with debug
The updated length is what the new mesh is suppose to be
but for some reason the mesh length is still at 600
strangely the hex in the middle vertices are removed
I recommend you just change the sprite color then
tutorial works
You have 2 error. Fix them ?
Hello im having a problem. Sorry if thats not the right channel for it. I downloaded and imported a asset pack but it seems it has no texture?
using urp
yup, working on it,
check the shader
in the mesh renderer, under materials tab
put in a default material i mean
or the proper one
This isnt a code problem
Thank you!
As i said , sorry if thats not the right channel for it(reading is important). However, you could just tell me where to send such problems next time instead of being a, well you know!
well, for visual related problems try the Artist Tools channels
or even the graphics
Great, thanks!
For some reason, my mesh.vertices is not updating
Are the error fixed ?
The error is caused by mesh.vertices not updating
so here is where I am at
initially, I have 600 vertices -- 6 per hex
I remove 1 hex -- now I have 594 vertices...
after removing the hex, I redraw the mesh by calling this method.
how ever the mesh.vertices size still stays at 600, even to the Vertices array size is at 594
the error is telling you it won't update vertices because that would make the previously assigned indicies in triangles invalid, try calling mesh.Clear() before reassigning the verts and tris
Well, this is a step in the right direction, thanks
now we have a new problem
You gotta update the triangle array also.
The triangle seem to not be correct.
Yes, however you are referencing vertex that no longer exist.
the indices themselves are wrong, you'll need to fix them before reassigning them, because you've changed the length of the array
And to be honest, have you consider using individual render component instead of manipulating the mesh at runtime.
no, never heard of standard render component
ATM, im just learning how to work with meshes really
I mean, 1 renderer per hexagone.
Yeah, it is faster, however do you need it to be faster ?
Because, it is also harder to maintain.
Meaning that you will lose time
Hmm, well the end goal is to have a means to modify the material of hexes individually
I guess 1 renderer per could be a better strat
Yes I agree reading is important. As the channel name, description, and #๐โfind-a-channel wouldve pointed you to the right place, you shouldve read them
your way isn't bad, but individual renderers will be easier to start with and you can see if it's a performance problem after that
Hey everyone! Does anyone know if the UGS Cloud Save has offline functionality, similar to Google Firebase?
well i am not a discord mod like you mate to know where every channel is and what purpose it has. Besides that, i am new to this discord server as i believe your eyes can see.
That is not a coding problem so this is the least relevant channel for this. #๐โfind-a-channel has a good explanation on each channel and your problem fits perfectly in one, if not multiple.
store it locally until you have internet
Thanks, no built in functionality then? We're looking to move from Firebase, their SDK just does it all automatically then pings the data off when internet connection is back.
In storing it locally, any suggestions on what way is best? Our save data is pretty large JSON, so I imagine we'll have to write a JSON file locally (mobile).
convert the materials
guys the problem is fixed!
.
yes cloud save on unity is still in its infancy.
yes you'd store the file locally, when you have internet on client again check and compare the files, handle overwrites / different files from there.
@thin aurora Someone helped me out already thanks.
Thanks for the help & confirmation, much appreciated.
cheers!
just curious is there a reason wanting to go from firebase to cloud save?
hello, is there any way to force trigger InputAction?
We've hit 132k users now, and we're no longer able to view or edit users data in 'realtime' on their dashboard.
I've been looking into it, it seems we have to export the data to BigData and edit it there, then reimport it to Realtime Database. It just seems like a headache.
gotcha. Have you looked into MongoDB Realm at all ?
not sure their cap but their datasync is pretty good
elaborate please
I have not, thanks for the heads up - I'll look into this.
UGS was interesting because we're already using Addressables, and we can use their remote config, authentication, vivox & multiplayer all under one roof. Just trying to simplify the project.
Is there any way to trigger InputAction in code?
E.g. I want to trigger InputAction.started one more time
makes sense. Yeah having all in one spot is convenient, def give realm a look tho . gl
The events are public, you can invoke them yourself.
even a public event can only be invoked privately
Oh right
Then use reflection
Reflection can bypass the internal and private stuff
Just don't add it as actual behaviour, only for testing
I cannot invoke it.
Hi guys, does someone know how to change position camera when sphere named "Player" will be in section ? (section - cube without collision)
what do you mean by reflection?
another method that will do the same stuff or what?
Reflection is a way to access class info that normal stuff can't do, so you can access the event and manually invoke it
I see, thanks
that's what I was aiming for
looks laggy because of the recording, there is 200 fps
basically when you hold e.g. D button, it moves right, and when you start holding W button, it moves up
holding A and D together makes Vector ofc (0, 0)
@rigid island http://www.s100computers.com/
S100 Computers Home Page
found some of these on ebay but most of them are in broken conditions or untested
expensive though 200+ for an old board xD
break out the soldering iron and osiciscope
haha yeah that's actually my next investment is oscilloscope
we've got a garage full of this shit dating back to '76. But we aint selling
yeah I wouldn't either, that stuff is priceless imo. History in the making
FirebaseDatabase.GetJSON(usersTableName , gameObject.name, "DisplayData", "DisplayErrorObject");
}
i am using this line to get data from firebase , but GetJSON is no calling the callback methods. can anyone tell me how can i call callback methods?
this isn't Unity related. Probably try firebase discord
this is unity related. if u work on firebase webgl
Try using nameof() for the method names
Who knows, you might've misspelled them
how's FirebaseDatabase at all related to Unity though?
you at very least should provide the source of the methods you used and how does it apply to unity
the docs for unity SDK shows a completely different method then what you showed . Where is this GetJSON method ?
i don't think so . here is my code. and second pic is of error that i am getting.
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
is it because I'm trying to reference the collision of two seperate game objects?
Idk, I don't use it
The error is not clear enough
And honestly, I can't work with "I don't think so". Just try it, and play around with the settings. One might fix it.
i mean misspelling of function name is not a problem , that's why i shared the pic of function where i am calling and which i am calling. it looks totally same. Thanks for suggestion , actually i used nameof() as well.
As u said u didn't use this, so its okay. Thanks again for your precious suggestion , it actually means alot for me. ๐
Hello I have this structure for an enemy. the Body is the actual enemy which moves but his body is the MainBody which rotates like a ball. I have a NavMeshAgent moving the Body and am manually doing mainBody.Rotate(agent.velocity, speed); to rotate the ball body as he's moving.
but this rotating doesn't fully match with his speed and doesnt look very nice.
Is there some math I can do with the rotation? I tried adding rigidbody to the MainBody but that causes it's own problems
Quick question, is there any diference between:
rb.AddForce(force1);
rb.AddForce(force2);
and:
totalForce = force1 + force2;
rb.AddForce(totalForce);
no not really
more force
oh, no
the same
haven't mentioned
And for best practice?
whatever makes your code more readable and organized
I would suggest 2nd one, it looks better
and more readable
Kk
does anyone know how to use monoinjector for c++
Hello everyone!
I wanted to ask real quick if I am overcomplicating something. I currently am working on a project where I have a skinned mesh renderer with multiple materials that happen to be render textures. My goal is to be able to receive a QR code and paste it into one of the textures. One resource said to use .Blit(), but that seems to replace a texture channel instead of combining them. Another resource said to create a custom shader that has a slot for the overlay texture.
I am trying to see if there is a resource already created within unity to work this out? Or if I am using Blit wrong lol.
You could either use a custom shader or modify the albedo texture
Ah, is modifying the albedo texture possible during runtime?
of course
Oh yeah I think I already am elsewhere in my project lol.
My unity seems to be .. doing something? to my sprites by just selecting them, prompting me to save changes. Any ideas?
Do you have a custom importer ?
Also, are you able to know what is being change ?
No custom importer, and no idea what's changing, although I could check git in visual studio
How can I use Vector2.Distance and apply object width/height into equation?
Currently the distance is measured from and to the center of an object.
I want a collision to check walls of both objects for the distance.
I can write the code for it, but perhaps there is a built in function for that?(I dont want to use built in colliders)
Are you doing manual collision detection?
Yes
It's very basic
It's not about collision, but rather checking the distance between objects.
well if you're not using colliders at all you'll need to do all the math yourself
The issue is that my units walk inside a building, instead of standing next to it in order to attack.
what represents the building?
I mean the building does use a collider
but the unit doesn't
buildings are axis aligned?
Because I dont use gravity which cuases units to do weird things when they collide.
Yes they are on the same Y axis
your options are:
- implement your own collision system
- work with Unity's physics (including perhaps physics queries)
units use navmesh?
if it's all axis-aligned boxes the collisions are simple to process
Units are not on same Y axis(a bit random, but close)
so if I use unity collision system, units start rotating when they hit with their "heads" lol
constrain the rotation on the rigidbodies
Is there a way to prevent any movement when collision occurs?
is that an RTS?
Or do I need to write a script for that.
Currently I loop through all active units + buildings to see if they are in "attack range"
No its a simple uh 2 side castle wars type of game
you send units on a straight path
played those
but with a slight random Y(just visual)
use physics save yourself headache
But I can't rely on collision detection for everything
Unless I add secondary collider as a trigger for unit attack range.
yes
Would that be a better way?
or use Overlaps
that's very standard
you can have as many colliders and triggers as you want on different layers
Do you mean this kind of overlap?
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
What is the nonalloc?
in your link click Physics, read the api
ah
It says that OverlapBoxNonAlloc this method will be depreciated in the future
and that I should use OverlapBox instead
this is true but you just use the overrides that are non alloc
but I think that I want a regular one either way? Since it returns an array of units?
which are the ones where you provide array or list for the results
if not then use non alloc and when, in the future, they replace OverlapBox with non alloc version, you can swap to it
the new overloads are already there
dont use the methods that return you arrays
in hotpaths
Collider2D[] The cast results returned.
yes dont use that
Why not?
it's for 2D
yeah I am on 2D
because you are allocating an array for each call
non alloc means no allocation
you create a buffer once and its reused
Looks like it's ... doing something related to the build target being webGL?
foreach (UnitBase unitBase in SpawnerSystem.Instance.ActiveUnits)
{
if (unitBase.faction != faction && isUnitInRange(unitBase))
{
unitBase.TakeDamage(damage);
return;
}
else if(isOpponentCastleInRange())
{
// Attack castle
}
}
I am already doing this lol, tho the List contains all units(including allied)
Actually, no, the build target is set correctly as windows - but I've recently installed WebGL as a module
(gamejam things)
And I do this to change unit state(which basically acts as a collision)
foreach (UnitBase unitBase in SpawnerSystem.Instance.ActiveUnits)
{
if ((unitBase.faction != faction && isUnitInRange(unitBase)) || isOpponentCastleInRange())
{
state = UnitState.Attacking;
return;
}
else state = UnitState.Moving;
}
Should I reimport all?
Is this bad enough that I should switch to Unity physics asap?
The game is small, nothing crazy
its not bad
Have you change your build target ?
private bool isUnitInRange(UnitBase unitBase)
{
float distance = Vector2.Distance(transform.position, unitBase.transform.position);
return distance <= attackRange;
}
Normally changing build target reimport all.
No, build target is (correctly) windows, but I did install the WebGL module for another project recently
That's how I determine that, so I need to apply Unit/castle width * 0.5 to the formula and it should work(Or maybe change Pivot for those)?
you can simply create a transform or a set of transforms that represent the stopping points for units and use them
I'm just gonna reimport all
this will be the most convenient way to manage it
What do you mean?
your building prefab, open it, create empty game objects, use them as points the units have to reach
oh you mean for the castle?
yes
Yeah I was thinking of creating a "wall" of sorts
Guess simple is enough for this ๐
how many units on screen?
I assume no more than 100(its a mobile game)
unitBase.transform.position cache this
dont use Vector2.Distance
compare square magnitude instead
What do you mean by cache? Does it update the position when the unit moves?
so if I make a list of unit postions it will keep track of it?
Tho I still need to access the Unit to check if it is the enemy unit.
yeah buildings dont move
thats why i said to cache
so I will have a List<Transform> units; then I have to do units[0].GetComponent<UnitBase>(); right?
For those units in range that I want to attack.
unitBase is not the building?
ah no
If I decide to move an object by changing it's transform directly, collitions won't work, right?
i assumed its a building
Its unit script that stores its information. Like a controller I guess.
If it's a rigidbody move it by using rigidbody.MovePosition
Trying to figure out how to not hard-code this
units[0].GetComponent<UnitBase>() to units[0]
where units is List<UnitBase>() already
basically dont make unnecessary calls to unity api
public List<UnitBase> ActiveUnits => activeUnits;
private List<UnitBase> activeUnits = new();
I do this
dont access transform unity apis, cache values that can be cached
so do I make second List to store position?
Because I need both position + UnitBase(it has functions like TakeDamge)
buildings, stopping points can be cached
yes thats what I thought
ok that makes sense
I made a mistake with how I wrote the code for castle spawning.
I have a class that has 2 instances for 2 castles.
But they vary a bit in how they spawn units(player presses a button, but enemy is automated)
Do you think its something worth fixing?
i dont understand the question
SpawnerSystem is where I store a List<UnitBase>
Basically I feel like I made a mistake with this class
I personally am a fan of strategy pattern for when you have 2 foos that do very similiar things, but slightly different
They are used by 2 castles(1 for player and 1 for AI)
Differences are:
[SerializeField] private int spawnDirection;
[SerializeField] private Faction faction;
[SerializeField] private Transform spawnLocation;
And the way units are spawned.
Yes basically my problem ๐ I have similar classes
So I just do some if's
if(faction == Faction.Ally) PlayerAction();
else if(faction == Faction.Enemy) EnemyAction();
usually i design such things in such way that the "spawner" becomes a factory that only does things that are externally requested.
then the user input becomes one user, and an ai script becomes another
this way your object has no idea who is using it and doesnt care
private void DoEnemySpawn()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
SpawnUnit(unitPrefab);
}
}
private void FixedUpdate()
{
if (faction == Faction.Enemy)
{
DoEnemySpawn();
}
}
And player spawn happens in a different script(its a button press) That is put on a button UI element
Both use same SpawnUnit(unitPrefab) function.
yeah so what you want is something like:
interface IFactionStrategy { ... }
class EnemyFactionStrategy : IFactionStrategy { ... }
class PlayerFactionStrategy : IFactionStrategy { ... }
public class FactionStrategyProvider
{
public IFactionStrategy For(Faction faction) =>
Strategies.First(s => s.Faction == faction);
}
public class YourClassHere {
void YourMethod(UnitBase unitBase)
{
var strategy = StrategyProvider.For(unitBase.Faction);
DoCommonLogicA();
strategy.DoFactionSpecificLogicA();
DoCommonLogicB();
strategy.DoFactionSpecificLogicB();
... // Etc etc
}
}
That sounds like what I should be doing.
So I am close to it, just need to move things out of the castleSpawner script into a more general Spawner script.
Then I can probably keep using shared CastleSpawner with few differences(spawnDirection + spawn location)
But thinking ahead, it's probably better to have separate scripts, since AI spawning will also have some sort of Spawner system with unit list/amount for different difficulty levels.
I need to look up strategy pattern, it's been a while and I doubt that I can implement your solution easily atm.
I pretty much wrote most of it there, thats about all there is to it
yeah but I need to understand it
I can't see where you use FactionStrategyProvider in the code
Is it StrategyProvider?
yeah you have an instance of it
or like, make it a singleton or whatever your way about it is
nah thats the method I declared in FactionStrategyProvider
I am afraid of linq, cuz it broken my old project for some reason and I never used it since then ๐
I just lambda'd it cuz its a 1 liner
ah
but what I wrote is the same as
public IFactionStrategy For(Faction faction)
{
return Strategies.First(s => s.Faction == faction);
}
So you store strategies as a List somewhere?
yeh
you can either do drag and drop with editor if thats your speed, or dependency injection, or service locator, whatever fits your workflow
So its almost like an if statement, but with extra steps?
I guess it has its benefits tho
You also could just store them in a dictionary instead of list even
So it returns a class either PlayerFactory or EnemyFactory and both of them share a script like .SpawnUnit
then itd just be
return Strategies[faction];
Which will be even faster cuz lookups on dictionaries are fast, and the assumption is you wont be registering more than 1 strategy per faction
so you don't need to do if(faction == player) doPlayerSpawnUnit();
yeh you'd just do
strategy.SpawnUnit()
But the issue I think is that player spawn units differently from the enemy.
it uses an UI button.
How do you put that into this pattern?(do you have to?)
Is it YourClassHere.YourMethod that you throw on a button?
I guess as long as the function knows who called it then it doesnt matter.(either player or AI)
yeah so, with the strategy, you already know who called it implicitly, cuz if its method is hit, it will just do its thing
public class PlayerFactionStrategy
{
public void SpawnUnit()
{
// We already know player is doing the spawning here, regardless of what called this, so we just focus on spawning the unit for player here and assume whoever called us knew what they were doing
}
}
This also opens up your ability to do stuff like, perhaps, have multiple ways players can spawn units.
Clicking UI will call PlayerFactionStrategy.SpawnUnit.
If they have an automatic spawner they built, that thing also just calls the same method.
If they have a unit that spawns a unit when it kills a unit... it would also call that method
etc etc, they all can just call the same method (and ideally you pass in some metadata about how/where/which unit to spawn
So maybe instead
public class PlayerFactionStrategy
{
public void SpawnUnit(UnitSpawnInfo spawnInfo) { ... }
}
That makes sense.
So I was going to ask, but you kinda answered with the second part.
Since I don't need to store the spawn location, PlayerFactionStrategy doesn't have to be a monobehavior.
eyup
Trying to get my player's input frame rate independent, but stumbling on a thing: I rotate the player's object based upon the mouse's horizontal axis (in Update), but if I multiply by Time.deltaTime the eventual rotation is faster at slower framerates then at higher rates?
float adjustedRot = (s_Input.mouseHorizontalAxis.ReadValue<float>() * setUpRotationSpeed * Time.deltaTime);
what am I doing wrong? the Time.deltaTime should smoothen that out, right?
Are you doing this in an Update or FixedUpdate?
update
I am using the "new" input system (hence the ReadValue). Is that just frame rate independent?
with axis
I believe that input axes already have deltaTime applied to them
They don't
Only mouse input is framerate independent
Mouse input has always been framerate independent
makes sense.. I was just checking on keyboard / controller axis and why they had the Opposite effect in regards to framerates as the mouse axis
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
Does the OnTriggerStay function trigger correctly?
I would also just change that var in OnTriggerEnter and OnTriggerExit
how to resolve this
What are u trying to do with this? The error tells u exactly what's happening, you have a dictionary that does not contain "None" which your enum does
Why are you using GameObject.Find?
thnxxx brooo !
solved
all I did was ask what you were trying to do and repeated what the error said
when i looked at my own screenshot, i understood lmao
I would still change this system a bit, you can loop over the dictionary with its .keys and .values or just really any way that you see on google. rather than attempting to store all its keys in an enum, because this will be fragile
Everytime u add to the dictionary, you'll have to type that into the enum
hmm 
By checking that the character is not null, its supposed to change the sprite over the safe zone to that character
huh?
Hello I have a gameobject with a navmeshagent and it has a child which is a sphere, I want to rotate that sphere in the direction of the NavMeshAgent.velocity. but idk how exactly the math works for that. the sphere should rotate/roll as if it has the agent.velocity itself and is on the ground.
I tried childTransform.Rotate(agent.velocity) but it doesn't work
if the character is found in the scene, the UI sprite is supposed change to show that character
All the characters have the "Player" tag so I'm using GameObject.Find instead if that's what you're asking
there's no need for either Find or FindWithTag
I have never had troubles with raycasts but now. Collision is just not detected. I have also drawn it with Debug.DrawRay
Vector3 newPos = transform.position + dir * moveUnit;
Ray ray = new Ray(newPos, Vector3.forward);
if (Physics.Raycast(ray, out RaycastHit hit, 10f))
{
transform.position = newPos;
print("hits");
}
Debug.DrawRay(newPos, Vector3.forward * 10f, Color.red, 100f);
yes, it does have Collider
show the collider gizmo?
also why are there 3 lines
becaue this method was called 3 times with different WASD directions
YOu're doing a 3D physics query against a 2D collider
Try Physics2D.GetRayIntersection
or use a 3D collider
do I check for null?
https://docs.unity3d.com/ScriptReference/Physics2D.GetRayIntersection.html
it returns a RaycastHit2D
https://docs.unity3d.com/ScriptReference/RaycastHit2D-collider.html
Note that some functions that return a single RaycastHit2D will leave the collider as NULL which indicates nothing hit. RaycastHit2D implements an implicit conversion operator converting to bool which checks this property allowing it to be used as a simple condition check for whether a hit occurred or not.
oh, actually I don't need to check for null, in converts itself
@leaden ice thank you, it works now!
This code still gives this error: . But I don't see the problem. I stopped the emitting process. I don't see a need to clear the things it has already emitted (and I don't want that to happen). Any ideas how to get rid of this?
it's telling you exactly what to do
won't that clear the existing particles?
damn that sucks
You could make the duration longer than what you need, or short and loop it assuming that's the same in your particle system. Then stop it after the duration rather than trying to change the duration at runtime
I was looking into the looping work around. Thanks !
just loop=true and using play and stop works like a charm ๐
The player characters are prefabs and are not within the scene until the level starts, so I have to call them this way
Not sure if this is a code or animation question, lets say I have 2 "types" of enemies "Melee" and "Ranged", who use an "Attack" state, but the animation is different for each "type" of enemy, everything else like movement, falling, etc are all the same between "types", what might be a good way to handle the different attacks? Should I make each attack its own state with a switch-case to play by name based on the type, or use a int animation param and assign each attack an arbitrary index or give each enemy their own animation contrroller? If the latter, how would I handle similar states like movement, falling, etc, since attacking and maybe 1 other feature would be the only differences between controllers
Are the animator state machines for each enemy the same?
Just different animation clips in each state?
e.g. same states, same transitions, etc
If they are - you should use this https://docs.unity3d.com/Manual/AnimatorOverrideController.html
Ah, ill try that out, thanks - yeah for the most part they are essentially "same states, transitions etc, different clips"
Why monobeheviours have persistant state between game launches and how to avoid this?
they don't unless you:
- are using static variables
and/or - are not doing domain reloads when entering play mode
I am not using static variables. I am not doing domain reloads when entering play mode.
But what I do, is not instantiating my prefab while editing its state.
you shouldn't edit prefabs at runtime
just as a general rule of thumb
and you should generally do domain reloads when entering playmode
but yeah any time you make changes to any asset (including prefabs, SOs, materials, textures, etc) in the editor it will be permanent
Why? How can I reduce character hp without editing it components? Or do you mean prefabs I am not instantiate?
you reduce the HP of the spawned character, not the prefab
Hey, is there any reason why you call the method .For? Is this a thing when using strategy pattern?
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
but also you're just assigning the sprite variable in your component. you aren't actually assigning the sprite to the sprite renderer
does anyone know how to make your game able to be fullscreened?
would I have to make some sort of button in the game to toggle between it?
hol on nvm
thank u :3
yep - that's how it works typically. In the game menu you typically have a setting for Fullscreen vs windowed
i was expecting, i can open Text Asset in VS code, simply for view and edit its content,
Is there a way to force scriptable objects to behave in the editor like they do in standalone build?
wdym?
So, as I understand it, making changes to SO assets in the editor changes the asset on disk. Making changes to a SO in a standalone build only persist as long as the application is running, changes aren't written back to the asset.
That's correct. Hence why scriptable objects should not be used as mutable data containers
the best answer is to not use scriptable objects as mutable data
You'll have to roll out your own save system (using JSON or similar) to make it work
but they are so convenient as a method of modifying instances of a prefab without having to hook much up
What happens when you right click the created asset and click reimport?
Also have you tried using System.IO.File.WriteAllText() instead of creating a TextAsset? This is what I use in my editor tools.
How can I get an array of coliders of all the players in the scene through their layermasks? Without using "Physics.OverlapSphere" or any other radius stuff
If your players all have at least 1 common script, you could use FindObjectsOfType<SomeScript>(), otherwise you could get all GameObjects in the scene and check each of their layers, store matching ones in a list and return the list (or use Linq), though either approach would be best done infrequently or not during gameplay, depending how your game works, there may be better ways you can just cache the players initially so you dont need to do a Find at all
When you spawn the players, put them in a list and remove them when they despawn.
Then you loop through the list to do what you want
okey thanks
I have a collider attached as a child to my player character and I'm using it as the hit detection for specific attacks. I have one (combat) script on the main character, and a script on the collider for using "OnTriggerEntry". Is there a way to communicate properties of the attack from the combat script to the on trigger entry script?
I could have it so that I have a reference to the on trigger entry script in the combat script, but that won't really work too well, so im hoping for an alternate solution
How about GetComponentInParent<CombatScript>() ?
I need help, I have a First person camera, how can I make so that the player can see the arms but not their own body, but still see other players body, and see their reflections on mirrors?
I saw having two meshes one for full body and one for just arms, and display one depending on wether its the player or other clients, but that wont show the players body on mirrors will it?
any thoughts?
You will need to have multiple cameras that render only specific parts of the player's mesh.
You can use the first person camera to only render the local player's arms but still render the remote player's body using the Culling Mask setting.
i'm having a bit of troubles with vector math, mainly because its a bit complex for me sometimes 
I'm currently making a detection system for my AI (pic down below), said dettection system knows the range (The yellow sphere gizmo) and a View Angle (In this case, the AI can only "detect" targets that are inside the two vectors (90ยฐ))
I'm already doing an overlap sphere and obtaining valid targets for the AI, the only issue now is to do a LOS check, in a scenario where the AI only has a cone view of 90ยฐ, i want the LOS check to return true only if a valid target is inside the cone view
how can i do this?
Fire multiple raycasts from one end to another.
i guess thats it, we can't open text asset via Code Editor, the extensions of file itself is .asset, so i do have option my data as json.txt but all because my personal preferences for using Text Asset, i didn't make that as txt, so all good for now,
I am trying to implement restarting my game by unloading and reloading my scene. But when I do that the scene seems to be in some midway state where a lot of the objects seem to carry over their previous state. I assume I am doing something nonstandard that's causing things to not clean up properly. Anyone have recommendation on what patterns to use to make the scene restartable? Or maybe tips on how to debug why my reloaded scene is in this stale state?
Do the objects that don't reset properly have any scripts in common? Or are they involved in some manager script at all?
no it seems like many scripts are in that state
but I am the common factor haha so maybe I jsut implemented the same bug in all of them
do you have any objects that you use DontDestroyOnLoad for?
Are all the objects existing in the scene or are they generated at runtime?
Almost all exist in the scene. Some UI widgets are generated at runtime.
Not directly but I might guess that Feel and DoTween do
which I usee
maybe they are holding references to things and I am not cleaning up properly?
For DOTween you should ensure that no tweens are happening when you reload.
I don't know what Feel is so I can't comment on that.
Do you mind spelling out for me what might happen if a tween is going on?
it might prevent GC of some objects?
Lots of NullReferenceExceptions for the most part. Some objects might remain on memory unintentionally.
Try calling DOTween.KillAll() before reloading the scene.
Of course without knowing what else happens in your code we can't tell if that's what's causing it.
for me tween maybe the culprit, as they usually dont destroy, so when you reload scene, your object is being destroy, but the tween still need it
you should stay with the overlap sphere strategy or even use a trigger collider and then calculate the angle between the targets and the direction the AI is facing.
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
Using a TON of raycasts to avoid the 1 math function is a shitty solution, for a bunch of reasons. Raycasts wont even guarantee that a target is seen if its within your LOS zone.
happens for me when using LeanTween too, so make sure you kill all the tween
cool thanks for the ideas!
Truly
Yeah I was like "I guess that works"
No way I'd do that cuz that's just awful for performance
It's not though but you do you.

worse performing solution, with launching many raycasts that wont catch targets in a ton of areas, vs a better shorter solution guaranteed to do what they want
yeah but that sounds like premature optimization
worry about performance when it tanks
ยฏ_(ใ)_/ยฏ
๐คฆโโ๏ธ
"premature optimization" doesnt mean you should opt for a worse performing solution that DOESNT work in every case
Friend of mine recommended using Vector3.Dot() and do some more math to determine if it was inside the view cone
But I think the angle idea you mentioned would suffice in this scenario
note how the issue i brought up here was "Raycasts wont even guarantee that a target is seen if its within your LOS zone"
I did not mention performance, although that is one factor
It will though
It won't lol
ok test it yourself.
there are these cases: Place an object lying down along the floor but its still in the LOS area. The raycast can go over it
Place an object above the raycast, the raycast will go under it
Stretch the LOS sphere to be massive, the raycasts will grow further and further apart
Then use spherecasts

@swift falcon don't cross-post
i see k ty
Either way no fuckin way I would spam casts for this
Why commit to a bad solution, you could just accept theres a better way. Its not preoptimizing to use a better and EASIER solution when it already is known. Its just dumb to stick to a worse solution
yeah sure
Makes me cringe thinking about it with X amount of AI running Y amount of raycasts every fixed update
I just prioritize faster iteration over making a "proper" solution that you probably won't utilize because you will drop the project halfway through.
ah i forgot to mention as well, regardless of what method you choose, you'll want to consider height as a factor. So if the player is above the enemy, do you want that to count towards the angle limit?
Hm yes I will drop my thesis project in the future 
If you do need to check for line of sight in addition, you can first check the FoV, then you can do some casts selectively towards the player from certain places you care about
Not really, I plan on doing the angle check first and ignore the Y positions by setting them to 0. if that succeeds, launch a single raycast to check if it actually is seeing the object or if said object is behind a wall
Ah yes i cant believe i forgot to mention that as well, once u find the target you should launch the raycast towards them to make sure there isnt a wall in the way
Aye
Ofc once both checks pass, the AI has a target and can begin attacking, which will be another can of worms I'm dreading to open but since my halfway point is approaching I'll have to do it anyways 
@steady moat A bit late, but that individual hex mesh idea is fabulous! thanks
I think through a weird GitLFS interaction I corrupted my whole project (except scripts which have confusing duplicates)... is there any hope to fix this? If I make a new project, how am I going to put it on Github without using LFS? Can I be sure it won't corrupt again?
When you clone your project, is the clone broken?
an earlier version should be completely fine, maybe some settings got messed up? did you push using the correct git ignore
from what ive seen recommended, people will send large files through other methods like dropbox or google drive
Can you try running git lfs pull in git bash
sure
didnt seem to do anything
okay, much earlier versions are fine, thanks for pointing me that way
Check any commits that modify .gitattributes
I'd backup the repo and try uninstalling lfs https://github.com/git-lfs/git-lfs#uninstalling
This is not really the place to ask these things #๐โfind-a-channel
More like #๐ฑโmobile
Alright thanks
my character is unstoppable with this movement:
if (hitInfo && hitInfo.transform.CompareTag("GameField"))
{
print("moved");
_rigidbody.AddForce(dir * moveUnit, ForceMode2D.Impulse);
}
it's literally flying
Impulse is intended for one-off forces, like shooting a cannon ball for example
I need to move my character so that it will be able to collide with other rigidbodies
teleporting with transform.position won't be good
doesnt matter what force u apply to it, it'll still be able to collide. with impulse you are just applying a lot more than you think
Why have you chosen Impulse?
to see if it moves fast enough
๐ค
the forcemodes are just equations
I see, I will try to change it to ForceMode2D.Force
it's the same with ForceMode2D.Force
it's just moving with small steps
well yes, u changed the equation used
yeah, it doesn't just move once. I want to do the same with Rigidbody as if I was doing:
tranform.position += dir * moveUnit;
We know
Just increase moveUnit
physics does tend to be different from teleporting objects (which doesnt exist in the real world)
also rigidbody2D has just 2 enum options
I'm sure you can figure it out then
I cannot actually. I need to move it on moveUnity that is 1f in my game = 1 "block" of unity
so the position is inted this way
Did you change it to Continuous or not?
yes
And it still goes through walls?
the issue is not that it goes through walls
the issue is that it doesn't move just once
lol the original question could have been phrased so much clearer
an object in motion will stay in motion, unless coded to stop - Newton probably
I AddForce just once and it moves with small steps (~0.05f) for infinite amount of time
my character is unstoppable with this movement:
it just moves forever
"unstoppable" would imply that walls couldn't stop it
In this tutorial, we will create a scoreboard and then increment (add) to the score when we collide with another game object. We will be using the FPSController to control the player and we will be collecting spheres that have a point value.
Donโt forget the rigid body.
Dont forget to put a Sphere Collider on both objects.
Remember to: Add a ...
any earlier tutorial for such thing ?
What does earlier mean in this context?
I see, maybe my English problems. It just moves as if I was moving it in Update with 10 fps
transform.position += 0.05f;
Either your character has no friction with the floor (physics material issue), which is the only thing that slows it down, or you are continually applying the force.
imagine you are rolling a glass ball (in real life) against a glass surface. It would continue to roll for a long time because nothing is stopping it. If you keep pushing it while it was rolling, it would never stop! Im simplifying here because real world obvious has resistances.
Think of rigidbodies as similar, nothing is stopping your rigidbody and you are constantly pushing it. If you want to stop it, you can use friction, drag, or manually slow down its velocity when no input is given
I see, my Player isn't even on surface
when adding velocity, you should restrict it to some maximum amount as well
it doesn't make sense if it's 3d game
but it's 2d
maybe you have any ideas how to make smth stop it?
or should I perhaps try another movement?
like I don't know how to make it, because it's not 3D and GameObject doesn't have z scale
the concept still works, there is friction and drag in 2D. you can also just apply a counteracting force when no input is given
is it reliable and efficient?
cuz I have never seen someone doing this.
Increase the linear drag on the rigidbody until it stops how you like it
you'll always have to adjust the numbers to get physics how u want it, its a lot harder to get an object to move exactly 1 unit by velocity compared to transform
maybe I should use Rigidbody.MovePosition instead?
sounds hard and not that reliable.
this really depends on what the object actually is, you would want the rb to be kinematic then
but MovePosition also doesnt care if objects are in the way
yeah, that's the issue here
do u even need physics on the object? Otherwise you could just move via transform and check if anything is in your path
At this point that's probably better for him
He had something going on with a coroutine, just chuck the checks in there
And done
yes, probably that's a great idea. I haven't understood the full behaviour of my game yet.
But actually makes sense if I just check OnCollisionEnter2D ๐ค
but the little issue is that transform will telepost it instantly
so my player will just stand on enemy if I just change its position
at that point using Vector3.Lerp does make sense, yeah? (that's question)
maybe not with OnCollisionEnter2D, but just by calculating your next position and seeing if anything is colliding with you at the new position
I see, I calculate distance between that collision and player and translate player to that distance when they should collide. Then end game
thank you all for your help @lean sail @quartz folio @winged mortar
I need help. I am fixing a bug in my game, where, if two bullets collide, the physics engine for some reason crashes, or takes an infinitely long time to process the frame. I found a fix, but it requires a collision to be detected. Is there a way to check for collisions before the physics engine, like, on update? I'm on 2d
๐ 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.
for context, this script is making the bullet snap back to the player after some time. I decided that if two bullets colide (they are called triangols) they will both snap back
latest version of Unity ๐ฌ
it's from 5 years ago, but I know it's legit
hmmm idea
what if I make a trigger that's bigger than the collider
so I get to trigger, without it messing up the physics
hello, we are trying to build our application on mac, using an M1 machine. Unfortunately whatever we do, it ends up at the same error, i will leave it here. It's Bee Artifact
We are using IL2CPP, and we are on unity version 2021.3.11f1
If somebody is able to fix this problem please let us know! We can't get anything to work on M1 machines
so, it's web build right?
no it's for mac
oh then i dont know
Your code doesn't seem to suggest something like this. Is this code the ammo code? And by crash, do you mean Unity shuts down unexpectedly?
So Unity utilizes roslyn compiler, and for the latest LTS version, the default c# version that Unity chooses is 9.0, however generally i know for instance on older Framework .csproj i can update language to "latest" to get some more modern feature. IS there anything like that in Unity? I tried changing csproj but it would revert to default 9.0
music still playing, nothing working
It seems like it's not a code problem tho.
Can you take a video of it happening?
Hey guys I have a quick question,
I have a float array (just a flat array) and I want to convert that to a Vector4 array. The memory layout should be the same, but the first array is just layout as floats. Prefferably just a cast no copies, is this possible at all?
Thanks a lot
How are you planning to convert a float into a Vector4?
i think he says a vector with 4 floats and wanting to make a v4 out of it
The converter is the way to initialize the array correct?
So effectively just a big loop over all the elements to initialize them?
yes, and you get to say what it does so in your case it can group 4 floats into a Vector4 and then skip the next 3 calls
Yea I figgured, thanks
I dont really think what I am looking for is possible
what? convert an array of floats into an array of Vector4, of course it is
if you have an array of 16 floats you can make an array of 4 Vector4's
Hi everyone,
Thank you for your time,
I'm getting a weird bug where I got the native file browser and choose a specific file but the callback only execute after clicking on the power button on Oculus Quest 2 wait a second then awake it (in other word putting it on sleep then awake it)
void Start()
{
NativeFilePick();
}
private void NativeFilePick()
{
//string[] fileTypes = new string[] { "audio/*" };
string fileTypes = "audio/*";
NativeFilePicker.Permission permission = NativeFilePicker.PickFile((paths) =>
{
if (paths == null)
Debug.Log("Operation cancelled");
else
{
print(paths.Substring(0,paths.LastIndexOf("/")));
FilePath = paths.Substring(0, paths.LastIndexOf("/"));
dir = new DirectoryInfo(FilePath);
info = dir.GetFiles("*.*");
CountFilesInDir();
}
}, fileTypes);
Debug.Log("Permission result: " + permission);
}
No, I know it is possible, but I dont think it will be performant enough for my use case.
Right now I am sending a float array to the gpu, and wanted to optimize this using a vector4 array. But if I am going to spend more time initializing the array every frame it isnt an optimization.
I was really just looking a way to cast it, or trick unity into thinking it is a vector4. Because the memory is layed out exactly the same way.
then you need to look at using unsafe code which will do that
basically a re-map of the array
Yea I tried looking for that, some pointer magic. But I couldnt work it out how to do it
learn C++
I know c++ ๐
have been using it for the past 7 years haha
I am well familiour with pointers in c++.
But for instance, unity doesnt seem to like to dereference pointers?
then it should not be a problem. C# is typesafe, C++ is not, so unsafe code in C# gives you the un typesafe facility you need
NativeArray should do it for you
Can I bind a native array to a material?
Or is it just a way to cast it?
to a material, no. to a texture used on a material, yes
wait what?
Hey, How can I suppress exiting play mode when a user presses play mode?
I want to show a dialogue box with yes and no button
open a dialogue box before stopping play mode unity
My list in a structure in a list is somehow getting edited (Count 1 to 0) without the second list getting read or set according to VS Debug, what's going on???
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
I'm using this interface for some nested classes inside of my SO and noticed that while debugging it's being constantly called even without making edits to the data. Is this intentional?
Really what I'm trying to accomplish is calculating and caching data with my nested classes while trying to keep the SO immutable.
I think this has to do with ScriptableObjects disappearing after a yield return
EditorApplication.wantsToQuit works when quitting editor not play mode
Any idea why my project keeps hanging like this? Deleteing my library & temp folder fixed it, but it's the second time this morning already.
Changes to the project include integrating Unity Authentication & Remote Config.
usually when it does like that after some time it works, and then next time is a lot faster. Try waiting 5 minutes before closing the window. Also check in the task manager whether the unity editor is allocating resources and moving memory around
Hey guys, I have a question concerning the performances of my game. Does using an event based system for my player Input rather than the Update function will improve the performance of the game or change nothing?
The last one was 55 minutes, before I killed the process. ๐
So I rebooted the project, hit play, fine. Made a change in my scene, saved it, hit play. Hangs.
very strange. what comes into my mind is: check how much the scene file weights, check if some plugins save stuff in the scene file. If deleting the library folder fixes it, i think it's a meta file problem, or maybe a cyclic reference that doesn't resolve
do you use Odin for serialization?
No. It should not change performance drastically.
There is a lot of other things that can be changed before.
No we don't, nothing too special in the project AFAIK. It was working fine until I started integrating the UGS stuff.
No, events are normal to use. You're just moving where the input polls to Unity's input system . . .
The question was about performance.
Event base Input and Input Pooling is different.
Alright, turns out I forgot to switch lists when deleting elements but more importantly, arrays and classes are passed by reference
Hmm, I'm also seeing these new plus signs & blue bars on my scripts - which I've added to this game object. Any idea what that means? We use GitHub for our repo, so if Unity is recognising changes, maybe there's a setting that has been changed.
This is because you added value to a prefab.
OK, so it's recognising the prefab change. So probably not the cause of my Unity breakdown.
Usually, when you have an issue that is hard to track, you roll back the change.
And try again, but slower.
You could also try to inspect what Unity is doing while hanging with a Debugger.
Then is also the Editor Log that can help you.
Do you mean using Debug Logs? I can't get into play mode at the moment, no matter what scene I'm loading. So seems like a project collision.
i'll try and find the editor logs, thank you.
No, I mean looking into the EditorLog files.
And using a Debugger such as Visual Studio
To stop the execution.
Thanks, but I see nothing.
It loads modules, posts an assembly line, then no other responses.
what ide is it?
That's the VS that comes with Unity
You gotta stop the execution of the code.
To see something.
Then you can go in thread section see what thread is doing work.
And, maybe, you gonna see a while(...)
(Also, be sure to attach to the Editor)
Thanks for your patience, just trying to figure out how to do this. Will google the steps.
Unfortunaly, this is not something you gonna find on google easily.
OK, so once I attach and it updates the console outputs - do I just hit Pause in VS?
Yes
attach the debugger to the unity editor instance, and set up a break point in visual studio. when that point in the code is reached, the execution will pause and you can inspect the values that are held inside your variables
The user does not know where it hangs.
They cannot set a debug point
You gotta inspect them, see it anything is out of ordinary.
A call to UGS by example.
You might, or might not be able to find something.
I am really able to find issue this way.
But sometimes, you see something obvious
Yeah
Try to see on what it is waiting.
Double click on void<LoadPlayerData>
You might be able to see
Anyway, it hangs on the loading of data.
Thus, you definitly have not correctly setup UGS.
I'm digging, I think it may just be code structure issues. Trying to resolve.
Yessss! Resolved, thank you.
I don't know if this is normal form, but following tutorials for integrations of UGS Remote Config & Cloud Save required that the player was signed into UGS Authentication.
So there was while loops in the Start functions, awaiting for the signing in to finish while (!AuthenticationService.Instance.IsSignedIn)
The thread were locking up in those functions, so I moved the loops to a seperate function and called them - code flowed and scene plays as expected.
As an example, this async await also seems to be hanging my project.
guys, lets say i would want to generate the outlines of a cube shaped grid. How would I do that?
LineRenderer
ty
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
part of it might be that I'm using GameObject.Find and gameObject.CompareTag, the reason this is here is becuase my player objects are all prefabs and can not be referenced through the inspector window, another issue might be that referencing a collision of two seperate gameobjects unrelated to the UI Sprite might be causing an issue, or at least that's as far as I can understand it
I have an idea for a game, when a door closes stuff change. How can i disable / enable an object visibility when closing the door?
uhh i have a problem with unity or a bug
do not crosspost
k
aren't these both event ?
what is the difference ?
public event Action MyAction
vs
public Action MyAction
I know Action is a delegate but what would be the difference here aside from 1 of them shows the lighting bolt on it ?
just for the sake of answering how i did it in case anyone else ends up on a similar situation.
if(awarenessAngle < 360f)
{
var potentialTargetPos = potentialTargetTransform.position.normalized;
potentialTargetPos .y = 0;
var bodyAimForward = aiBody.AimOriginTransform.forward;
bodyAimForward.y = 0;
var max = awarenessAngle / 2;
var min = -max;
var angle = Vector3.SignedAngle(potentialTargetPos , bodyAimForward, Vector3.up);
//Hurtbox is not inside vision cone, continue to next candidate
if(!(angle > min && angle < max))
{
continue;
}
}```
main difference is that an event may only be invoked by the class that declares it, while non-event delegates may be invoked from any object with access to that var
under the hood there are way more changes, e.g.: how the compiler treats those fields, and what is accessible via reflection
also, for events there're two special keywords: public event Action MyEvent { add => ..; remove => ..; } -- and cannot do 'get; set;'
Oh ok that make sense, thanks!
https://gyazo.com/e1f2c054774e57b1fbb80516405b3084
here is a video better showing my issue
at first when i try hover over the brown box nothing happens when it should be triggering my OnMouseOver
however for what ever reason if i turn isTrigger on and then off it seems to work
which dosnt make any sense to me
Hi Nebby, I saw your post and thought I'd share my idea of what should also work. I haven't tested it though.
bool IsTargetInAwarenessCone(Transform target, float coneAngle)
{
return IsTargetInAwarenessCone(target, coneAngle, transform.forward);
}
bool IsTargetInAwarenessCone(Transform target, float coneAngle, Vector3 coneCenter)
{
var selfToTarget = (target.position - transform.position).normalized;
return (Vector3.Dot(selfToTarget, coneCenter.normalized) >= Mathf.Cos(coneAngle * Mathf.PI / 180f));
}
Hi, I have a problem: when creating a property drawer, I have a property that shouldn't be drawn but for some reason it's still drawn.
So the question is: is a list considered a property that can be not drawn??
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (ShowMe(property))
{
...
}
else if (drawIf.disablingType == DrawIfAttribute.DisablingType.ReadOnly)
{
...
}
Debug.Log("Not drawn");
}
that log statement will run no matter what
But the property is drawn only if the ShowMe() is true or the disablingType is Read only
the debug line is outside everything
so no code should be run
exactly so it will run always.
only if it's in an else will it run only when the others don't
#archived-code-general message anyone have any ideas?
if (ShowMe(property))
{
...
}
else if (drawIf.disablingType == DrawIfAttribute.DisablingType.ReadOnly)
{
...
}
else {
// not drawn
}```
I just added it in the else statement but it still debugs
you'll have to show all your code and explain which property is being drawn that you don't want to be drawn
Can I send it through pastebin?
you should yes
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.
https://pastebin.com/1sJzppdT For the property attribute
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.
DialogueManager.GetInstance() is returning null
presumably you don't have a DialogueManager in the scene or something along those lines
Here the list is drawn always
public bool completionSetOtherQuestsAccessible;
[DrawIf("completionSetOtherQuestsAccessible", true)]
public List<string> questIDToSetAccessible = new List<string>();
you're showing little bits and snippets and not really fully explaining the issue exactly. It's also unclear what DrawIf is and how that works
it's hard to help only seeing little snippets
oh sorry i see the pastebins now
Tbh i'm not really sure, but instead of writing a custom DrawIf attribute I would recommend using NaughtyAttributes which definitely works
https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
I saw it while I was researching but I still wanted to try something on my own
I'm not sure it worked with custom classes
of course it does
guess i'll have to go that way
EditorApplication.wantsToQuit works when quitting editor not play mode
I want to show a dialogue box with yes/no button when the game is playing in the editor (play mode) and if they press play button in game window to close the game (editor), shows the dialogue box and if they press No button, don't quit play mode.
You could create your own system - on a button click, show your dialogue, if yes is hit, all Application.Quit(), otherwise hide the dialogue, you could set it up with a callback if youd want, or just have your dialogue trigger with a function that accepts a System.Action as a param for what to do if "yes" is clicked
No, It is not my scenario
Play button in game window
I want sometimes it does not work
Ah, you should be able to call EditorApplication.isPlaying = false when you click "yes" on your dialogue if its to exit play mode from the editor only, and not at runtime/in a build
Can someone please tell me how I screwed this up?
Whenever I press the S key (backwardMovement) it is setting to false instead of true. I keep looking this over and it looks good to me.
void HandleMovement()
{
bool isRunning = animator.GetBool(isRunningHash);
bool isWalking = animator.GetBool(isWalkingHash);
bool isWalkingBackwards = animator.GetBool(isWalkingBackwardsHash);
if (!movementPressed && (isWalking || isWalkingBackwards))
{
animator.SetBool(isWalkingHash, false);
animator.SetBool(isWalkingBackwardsHash, false);
}
if (movementPressed && !isWalking && !isWalkingBackwards)
{
if (currentMovement.y >= 0 && !backwardMovementPressed)
{
animator.SetBool(isWalkingHash, true);
}
else if (currentMovement.y >= 0 && backwardMovementPressed)
{
animator.SetBool(isWalkingBackwardsHash, true);
}
}
if (movementPressed && runPressed && !isRunning && !backwardMovementPressed && !isWalkingBackwards)
{
animator.SetBool(isRunningHash, true);
}
if ((!movementPressed || !runPressed || backwardMovementPressed || isWalkingBackwards) && isRunning)
{
animator.SetBool(isRunningHash, false);
}
if (currentMovement.y > 0)
{
transform.Translate(transform.forward * moveSpeed * Time.deltaTime, Space.World);
}
else if (currentMovement.y < 0)
{
transform.Translate(-transform.forward * moveSpeed * Time.deltaTime, Space.World);
}
if (backwardMovementPressed && !isWalkingBackwards)
{
animator.SetBool(isWalkingBackwardsHash, true);
}
else if (!backwardMovementPressed && isWalkingBackwards)
{
animator.SetBool(isWalkingBackwardsHash, false);
}
}
And yes, the input has a value of -1
use debugger
No idea as to how debugger works, which is why I posted this here in case anyone could spot something simple, but I guess I will figure out debugger.
hey where should I go if i want wwise help? they don't have a discord
thanks ๐
I have an update on my question. The attribute works perfectly with custom classes and normal atributes like int, floats, strings
Apparently the problem is with Lists and Array
So lists are always drawn no matter what?
doubt it, i just cant dedicate mental resources to simulating your code atm sorry
Wait just quickly if I have a static variable and I assign it at some point, does creating another instance also carry the value of that variable over?
I'm trying to understand singletons
I know how to do them but just why
Static variables only have one instance and the value is shared between classes
Ah right that makes a lot of sense now
If you took a generic enemy script and made their current HP a static value, hurting one enemy would hurt every one of them
A practical use would be for easily referencing something like in my game, the settings menu object
Yeah static now that I've had it be said simply makes so much more sense
Seems really useful definitely going to be using it
If you want to do that to a class you can make a static member referencing the same class, then on Awake() you can do reference = this
Look up singleton patterns in unity thereโs a ton of examples and use cases
You might want to destroy any copies of that class in Awake
Yeah I've done so already was just curious what the point in them was when say I could make a DDOL GameObject with a script on it
every class has a static version, a static class is also an instance class, but you are not allowed to manage it, the .net is managing it for you, and allows you to access it through static members, so it is by itself already a singleton in its purest form
For my script, I'm trying to make it so that once the player steps on a "SafeZone" a place where they can change their character, it updates a Ui sprite showing what character they are. The variable currentCharacter doesn't seem to be updating even when the "Player" is colliding with the "SafeZone". Here is the code.
https://paste.ofcode.org/63uE92nHJKKHYcxgmn6SwV
Does this have something to do with how I'm referencing the collision of two seperate gameobjects?
In my case I dont expose the static reference as public, I just expose methods like
public static bool IsOpen() {
return instance != null ? instance.isOpen : false;
}
So i can use SettingsMenu.IsOpen() to see if the menu is open or something, disabling player movement input while the menu is open.
That makes way more sense tbh
that also leads to bigger refactor time later
i have two cubes perfectly lined up together and for some reason when the player rolls over them, the collision normal isn't (0, 1, 0). anyone know why?
even when theyre on the same y level?
how do you get the collision?
rbs generates a bunch of collision points for each collision
those can be all over the place, inside the collider, on the surface etc
// Player Knockback
private void OnCollisionStay(Collision collision)
{
Vector3 normal = collision.contacts[0].normal;
Transform transform = collision.gameObject.transform;
if (
(collision.gameObject.tag == "ground" && normal != transform.up)
|| collision.gameObject.tag == "enemy"
)
{
Debug.Log(normal);
//Debug.Log("c1:" + (collision.gameObject.tag == "ground") + ", c2: " + (normal != transform.up) + ", c3: " + (collision.gameObject.tag == "enemy"));
rb.AddForce(normal * pooshAmount, ForceMode.Impulse);
}
}```
yeah check how many contacts there are in that array
use debugger
that tutorial doesnt seem to use rb contact points at all
oh im wrong there is
im not trying to snap the player to the ground though i just use a tilemap for grounds so a 3x3 of evenly hieghtened cubes should really act like 1 surface
there is no "single contact" point
you have to extract the information relevant to you from a set of generated contacts
like in the screenshot above
oh so like
theres a point in time where im colliding with 2 different objects at once so i can check the y value of the player within a threshold
yeh?
even 1 object generates multiple collision points
but my issue is only triggered by rolling over the 2 not when the ball is only on 1
use physics debugger
it will show you precisely where the contacts are
so you can visualize what is going on
its a marble game
the player is a sphere
and im trying to make it so the player knocks back on the sides of walls (anything that isnt transform.up)
In WebGL builds, i've tested by creating builds in unity 2019, 2020, 2021 and 2022 of just a new project with the sample scene, Everything loads fine when i host the builds on itch.io but when i try to host the builds on the server at the company where i work the build just hangs past unity 2019. Unity 2019 and earlier work fine but 2020, 2021 and 2022 get stuck like you see in the screenshot there.
Can anyone think why this might be the case that WebGl doesn't seem to work so well anymore after 2019?
If you're doing any async loading there could be issues
just from previous experience pre-loading a bunch of data
Open the dev window on your browser and see if it's throwing any errors
Is GetComponent from gameobject is noticeably faster than .gameObject from component?
no
it's almost definitely slower actually, but definitely not noticeably in either direction
So it is faster to targetGO.GetComponent<MyComponent> than myComponent.gameObject?
you almost never need a GameObject type variable, it's typically better to reference the component rather than the gameobject in nearly all cases and just get the gameobject from the component if you need to access it for whatever reason
Trying to think,
so would the worst case of a 16x16x16 chunk mesh where only exposed faces are rendered be this?
I'm trying to reduce garbage collection so I would want the chunk to have a vertex array probably to fit this
that's completely the opposite of what I said
Oh, right
Your original question was "Is GetComponent noticeably faster than .gameObject"
I responded: "no it's slower"
they're both fast enough that you usually don't need to worry about them from a performance perspective. I'd just argue GetComponent is ugly and less readable than using .gameObject on the rare occasions you actually need a GO reference
code readability is the bigger issue
Yeah I'm comparing go.GetComponent<Rigidbody>() with myRb.gameObject though which is a different subject
So is it reasonable to create dictionary with a GameObject as a key and component as a value instead just list of components to cut additional GetComponent that will be called a few times every frame at maximum?
no
completely not reasonable
As I said before:
they're both fast enough that you usually don't need to worry about them from a performance perspective.
if you are calling GetComponent a few times every frame you're doing it wrong
call it once and save the reference in a variable
or better yet - don't have a damn GameObject reference in the first place
I have list of rigidbodies and I need to remove the ones that was destroyed. My onDestroy event passes gameObject, so if I store only rigidbpdies, I'll need to destriyedObject.GetComponent<RigidBody>() every time I need to remove rb from list.
My onDestroy event passes gameObject
Make it pass a Rigidbody instead
This was a component that can be on objects without rb, seems not very convinient to have different ones.
then use GetComponent here - not a problem. How many of these things are actually happening anyway
I fear you may be trying to prematurely optimize
are you actually seeing a performance issue here?
Have you profiled the game and saw "oh my GetComponent is really killing me here"
Yes. I have modifier that controls movement, it stores all active projectiles and apply some force to them.
No, just asking how it is usually done ๐
it sounds reasonable to use GetComponent here - though if OnDestroy event is happening for objects that don't have Rigidbodies I would be using TryGetComponent
Doesn't GetComponent just return null if there is no such component?
yes which is uglier than using TryGetComponent
Thanks will take a look
if (obj.TryGetComponent(out Rigidbody rb)) {
allBodies.Remove(rb);
}```
is cleaner than:
```cs
Rigidbody rb = obj.GetComponent<Rigidbody>();
if (rb != null) {
allBodies.Remove(rb);
}``` @hollow hound
Thanks
Anybody familiar with this? Works on Editor. Breaks on WebGL.
var count = fileStream.Read(bytes, sumLoaded, readSize);
I am doing getComponent when projectile is created and adding rigidbody to list. I am also subscribing to onDestroy event of gameObject. Then in update I am apllying force to projectiles. And in HandleDestroy (which passes gameObject) I want to remove rigidbody from list. And if i'm not using dictionary here, I'll need to destroyedGO.TryGetComponent every time it destroys. Which can be ok from the performance side, but I'm not sure so asking this. ๐
it's fine
you will get a much better performance improvement by swtiching from a List<Rigidbody> to a HashSet<Rigidbody>
You also should only be adding forces in FixedUpdate not Update
Thanks
Hey sorry this might be a simple question but I'm not sure how I should make it so that an object moves indefinitely in the forward direction during runtime (aka along the blue line in the editor)
while being affected by its rotation
I've had a few problems coding a script. Basically, the player has the ability to change character, and I want a Ui sprite to update once that player switches character. I've changed the script a few times but currently it only seems to update the sprite to that of the first character, and doesn't change to the second or third. My question is why doesn't the script update currentcharacter for the second and third else if condition?
https://paste.ofcode.org/EtdCvDqFbLkyFHDJpVqkxn
Also the UI sprite has its own script that takes the currentCharacter of this script and makes it its own, in case that helps explain it
transform.forward will refer to the local z of the object (unless changed), you could add that value, multiplied by some speed to the current position, if it needs to also respect physics, you could add that as a velocity instead of setting the transform posittion
oh i didn't know i could just add transform.forward to a position directly
thanks a lot
here's the line if anybody's interested
transform.localPosition += transform.forward * speed * Time.deltaTime;
I would maybe use an event so you can separate your logic a bit more, for example:
public class CharChanger : Mono
{
public static Action onNextChar;
int next;
void Update()
{
if(someInput) {next++; onNextChar?.Invoke(next);} //however you want to handle "changing characters"
}
}
public class CharViewer : Mono
{
public Image display;
public List<Sprite> chars;
void OnEnable() { CharChanger.onNextChar += NextChar; }
void OnDisable() { CharChanger.onNextChar -= NextChar; }
void NextChar(int index) { display = chars[index]; }
}
Not verbatim code, though in this case, the "changer" is your player logic or whatever handles switching characters, that fires the event - the "viewer" listens for that event and updates UI in response - there are many ways you could improve that kind of implementation (you could wrap the index or modulate it so its never less/greater than your sprites, you could store the sprites in a ScriptableObject and use that instead of a index, etc)
Hi, i have a rotation problem.
i have a 2D tank that can move and rotate itself, and a turret child object which I want to have a specific FOV angle it can turn towards in relation to the parent object.
i tried too many methods and none seemed to work, i still struggle to comprehend all rotation types properly and maybe thats why.
I tried sharing code here, but discord's Clyde said it couldnt be delivered ๐ . I guess discord doesnt like me sharing code.
Not blaming this server btw. So i'll try to give the code in parts.
Dictionary:
front_mg_target = game object that is defined properly elsewhere.
front_mg_weap_obj = our mg turret object
Various coroutine variables are defined elsewhere.
flaot front_mg_rotate_speed is defined.
// called in Update()
private void FrontMGAimLogic()
{
if (front_mg_target != null)
{
if (Vector3.Distance(front_mg_target.transform.position, front_mg_weap_obj.transform.position) < range)
{
if (resetFrontMGCoroutine != null)
{
StopCoroutine(resetFrontMGCoroutine);
resetFrontMGCoroutine = null;
}
Vector3 directionToEnemy = front_mg_target.transform.position - front_mg_weap_obj.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, directionToEnemy) * Quaternion.Euler(0f, 0f, 0f);
if (rotateFrontMGCoroutine != null)
{
StopCoroutine(rotateFrontMGCoroutine);
rotateFrontMGCoroutine = null;
}
rotateFrontMGCoroutine = StartCoroutine(RotateFrontMG(targetRotation));
}
else
{
if (resetFrontMGCoroutine == null)
resetFrontMGCoroutine = StartCoroutine(ResetFrontMGRotation());
}
}
else
{
if (resetFrontMGCoroutine == null)
resetFrontMGCoroutine = StartCoroutine(ResetFrontMGRotation());
}
}```
private IEnumerator RotateFrontMG(Quaternion targetRotation)
{
while (front_mg_weap_obj.transform.rotation != targetRotation)
{
front_mg_weap_obj.transform.rotation = Quaternion.RotateTowards(front_mg_weap_obj.transform.rotation, targetRotation, front_mg_rotate_speed * Time.deltaTime);
yield return null;
}
}
private IEnumerator ResetFrontMGRotation()
{
yield return new WaitForSeconds(3f);
Vector3 directionToEnemy = tank_mg_base_lid.transform.position - front_mg_weap_obj.transform.position;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, directionToEnemy) * Quaternion.Euler(0f, 0f, 0f);
while (front_mg_weap_obj.transform.rotation != targetRotation)
{
front_mg_weap_obj.transform.rotation = Quaternion.RotateTowards(front_mg_weap_obj.transform.rotation, targetRotation, front_mg_rotate_speed * Time.deltaTime);
yield return null;
}
resetFrontMGCoroutine = null;
}
```
That's all, please ping me if you have anything
{
[Header("Layers")]
public LayerMask groundLayer;
[Space]
public bool onGround;
public bool onWall;
public bool onRightWall;
public bool onLeftWall;
public int wallSide;
[Space]
[Header("Collision")]
public float collisionRadius = 0.25f;
public Vector2 bottomOffset, rightOffset, leftOffset;
private Color debugCollisionColor = Color.red;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
onGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomOffset, collisionRadius, groundLayer);
onWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, collisionRadius, groundLayer)
|| Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, collisionRadius, groundLayer);
onRightWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, collisionRadius, groundLayer);
onLeftWall = Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, collisionRadius, groundLayer);
wallSide = onRightWall ? -1 : 1;
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
var positions = new Vector2[] { bottomOffset, rightOffset, leftOffset };
Gizmos.DrawWireSphere((Vector2)transform.position + bottomOffset, collisionRadius);
Gizmos.DrawWireSphere((Vector2)transform.position + rightOffset, collisionRadius);
Gizmos.DrawWireSphere((Vector2)transform.position + leftOffset, collisionRadius);
}
}```
How can i do this type of gizmos but with squares so it fills the bottom side and the same with the sides? since my player is a square and the circle doesnt fit all the way to the sides/bottom
No, It does not work. I have tested it before.
It freezes the game (play mode)
You sure? I just tested this code, and 3 seconds later, it automatically exits play mode, if its freezing, maybe something else is going on:
void Start()
{
Invoke(nameof(Test), 3f);
}
void Test()
{
EditorApplication.isPlaying = false;
}
Any ideas on how I select an environement (dev, prod) in UGS Cloud Save?
I've managed it for Remote Config, but can't find the function in their manuals.
Need some help!
I'm using this script for a drawing mechanic, however, the colour only changes if I set it like this
{
BrushColor = Color.green;
}```
I want to set it via a colour picker in the inspector but when it is set that way it seemingly ignores the colour in preference of one set via Color.green, Color.red, etc.
This is how BrushColor is set
```public Color BrushColor = Color.black;```
The debug on this script outputs an RGB value but doesn't actually change the colour
``` public Paint brush;
public Color color;
public void ChangeColour()
{
brush.BrushColor = color;
Debug.Log("Colour set to" + color);
}```
Here is an example of how I have set up a use of the ChangeColour() mechanic
is the RGB value correct from what you chose in the inspector? because this function doesnt take any parameters so im unsure where color even would get its value from
is there anymore code to this?
There's the entire painting code but not sure if it's relevant
it just seems like this function just needs to take in the color to actually change it to then
The "color" variable that is used in ChangeColour() is set in the inspector
oh damn i missed that part
All good!
for public Paint brush;, are you assigning using that reference to actually draw as well?
i think you might be changing the color on another instance of the class
Also, are you setting BrushColor elsewhere?
I don't believe I am?
Can someone tell me how , when using netcode for gameobjects , I can spawn a player object for both host and client when its bult for standalone but for android only the host spawns a player object not the client
The Paint script is what I use to set up the painting mechanic
Weird thing is that it shows up with the changed colour in the inspector for the Paint script but doesn't actually "draw" with that colour
Then surely those are two different things
if it's changing in the inspector then the code is working fine
This is the actual painting code
private void DrawOnTexture(Vector2 localMousePosition)
{
float u = (localMousePosition.x + rectTransform.rect.width / 2) / rectTransform.rect.width;
float v = (localMousePosition.y + rectTransform.rect.height / 2) / rectTransform.rect.height;
Vector2Int currentPixelUV = new Vector2Int((int)(u * texture.width), (int)(v * texture.height));
Vector2Int previousPixelUV = new Vector2Int((int)(previousMousePosition.x + rectTransform.rect.width / 2),
(int)(previousMousePosition.y + rectTransform.rect.height / 2));
// Calculate the brush size in pixels
int brushSizePixels = Mathf.RoundToInt(BrushSize * texture.width / rectTransform.rect.width);
for (int x = currentPixelUV.x - brushSizePixels / 2; x < currentPixelUV.x + brushSizePixels / 2; x++)
{
for (int y = currentPixelUV.y - brushSizePixels / 2; y < currentPixelUV.y + brushSizePixels / 2; y++)
{
if (x >= 0 && x < TextureWidth && y >= 0 && y < TextureHeight)
{
float normalizedDistance = Vector2.Distance(new Vector2(x, y), currentPixelUV) / (brushSizePixels / 2f);
float brushIntensity = Mathf.Clamp01(1f - normalizedDistance);
Color currentColor = texture.GetPixel(x, y);
Color blendedColor = Color.Lerp(currentColor, BrushColor, brushIntensity);
texture.SetPixel(x, y, blendedColor);
}
}
}
previousMousePosition = localMousePosition;
texture.Apply();
}```
Id suggest making a property/setter function so you can debug what the old and new value of BrushColor is. Maybe it is setting on a separate instance then
Alright it's definitely not setting correctly then since it only debugs when I use the Color.green method not the custom inspector one
The colour set is showing the correct values in the inspector but the RGBA (what's actually being drawn) is clearly not the same
Another weird thing i found is that the colour picked drawing actually works when I have a buffer zone where the drawing is meant to be "disabled"
is there a way to have two camera follow the same movement but only having one active at a time?
Do you want to be able to toggle between them?
yeah so i'm doing a game where the character transforms into 2 different modes so i have two cinemachine cameras set up
Im sitting here staring at this debug output and I cannot for the life of me see why my continue didnt get hit, am I tired or does this logic check out, and I should 100% be hitting that continue? Or is this some kind of weirdness with comparing Vector2s?
oh damnit nevermind now I see it, third part is supposed to be .Contains(neighbour) not to fml lol
Though I'd be careful with comparing vectors like that. If they don't have decimal part, might be wiser to use Vector2Int.

