#archived-code-general
1 messages ยท Page 94 of 1
yeah i changed it, still doesnt show
it should still work fine
apparently not
what is HeartType
show me a screenshot of the HealthManager component in the inspector.
also, what version of unity is this?
have you also made sure to save your HealthManager script after adding the list field?
2021.3.11f1
i would ensure this, yes..
yep. I assume its something to do with the unity engine/library cause there doesnt seem to be anything wrong with my code
and make sure that compilation happens -- you should get a popup for a few seconds
and then console should be empty.
click the HealthManager script in your assets folder and look at what it shows in the inspector. do you see what you are expecting to?
yep, also regenned meta files a few times
and also deleted and remade the scripts
reimported all
and reloaded unity
Do you have a custom inspector set up for that script? I would expect the file name to appear in a read-only field at the very top of the component
nothing fancy at all just a couple of floats and values
that's not what SPR asked
they are asking if you've defined a custom editor for this class
no, no custom inspectors i mean
it sure looks like you do, because there should be a grayed-out field called Script at the top
damn your right might be onto something there
name the class (and obviously the script file) something different (without using the actual refactoring tools) and remove then re-add the component and see what happens.
no i dont but that could be a clue
ctrl-shift-f your project for CustomEditor
can you screenshot inspector for HealthManager but in Debug Mode
yes ok so a new script called Test2.cs works fine at displaying the health
it for sure sounds like you have a custom inspector for that type that you need to find and fix (or just stop using altogether)
yeah i think thats it mightve been a custom inspector i deleted and forgot about
Please do this
Search all the files in your project for custom inpectors
has to be, also you're missing this on your script
the dots! the dots!
wait nvm I thnk the screenshot is just cutoff
in debug mode though you should be able to see if it's correctly link
oh i see CTRL SHIFT F on VScode
when someone asked if you had custom inspector doesn't that click to be a reminder of what you did ?
no i thought that custom inspector was affecting a UI class not the health class itself
plus i wrote it ages ago thought its not worth the effort and left it alone
I've already documented these debugging steps for anyone that doesn't want to waste time in future https://unity.huh.how/programming/serialization
yeah thanks for that
bookmarked
nice too see Debug mode is mentioned ๐
thought I yelled at deaf ears
If you had a custom inspector for your UI class, and your UI class is holding a reference to your health/hearts, then Unity would let you handle drawing the variables you choose instead of serializing them for you
damn you really got everything covered. your site is such a gold mine of troubleshooting tips
damn this is actually cool thanks
I also updated the physics messages one with a sidebar and better clarity at the start based on the last annoying one we ran into a day or two ago
Speaking of physics, I came across your shape debugger for raycasts and such a while back, incredibly helpful git
Hey. Is there a way in unity to instantiate a unique scriptable object at runtime?
I have a chest prefab that stores items. If I have a second chest that can be spawned by the player, i need it to have a seperate inventory than the first chest. How can I do this?
On the script attached to the chest, I've tried:
_chestInventory = Instantiate(chestInventoryBlueprint);
chestMenuPrefab.inventory = _chestInventory;
(where chestInventoryBlueprint is an InventoryObject that is set up how I want all my chests to be set up ie number of slots, allowed items in each slot, etc...) in the start() method. The inventoryobject. is a scriptable object However, it seems like if there is a second chest prefab in the scene, they still share the same inventory with each other.
so removing an item from one causes the other to also lose an item?
does this also modify the original asset?
No, the blueprint is not modified. And yes, removing an item from one causes the other to lose it
Like its succesfully creating a clone of the blueprint, but the problem is that all the prefabs share the same clone
i wonder if they're winding up with the same list reference
but since it's serializable, then i wouldn't really expect that...
Instantiate makes a unique object
if you call Instantiate on a ScriptableObject is clones it, including the currently set properties, no? Wouldn't it make more sense to use CreateInstance to create a brand new instance of the ScriptableObject with none of the properties set to the existing values?
Your question pivots on what kind of data exactly is stored inside the SO and whether it's serialized, etc...
_chestInventory = InventoryObject.CreateInstance<chestInventoryBlueprint>();
As in this?
thisis what i was referring to https://docs.unity3d.com/ScriptReference/ScriptableObject.CreateInstance.html
but you have to provide more context
at the very least: one paste for the SO, one paste for the chest
_chestInventory = Instantiate(chestInventoryBlueprint);
chestMenuPrefab.inventory = _chestInventory;
If I have a quaternion that is made using Quaternion.LookRotation(direction) and I want to rotate the quaternion along the direction axis by X degrees, how do I do it?
i am asking you to share the entire script
we are looking at random lines of code here
it's like trying to debug through a mail slot
Like I have a capsule that has no rotation (so it points up and so the direction is Vector3.up) how do I rotate the capsule along Vector3.up???
The script for which? The chest object or how the inventory system works?
In the chest script that is the only code
^
no, that is not the only code, because that would not be a valid C# class..
that references the inventories
๐ 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.
One min, i want to try using the other method really quick. For the creating instance suggestion,
'''
_chestInventory = InventoryObject.CreateInstance<InventoryObject>();
'''
is there a way to make _chestInventory inherit all of the properties of the blueprint now?
you have not shared your code
i am not going to provide advice until you share your code
wasn't the entire issue that you thought all of the inventory things were using the same instance of the scriptable object because they shared the same property values?
but seriously, you need to share more context or you won't get accurate help
The issue is that at runtime, any changes to one would affect the other. I wanted them to be instantiated with the same properties to start, but when the player is interacting with them it only affects the one
well you still haven't shown enough context so until you do you're not going to get any help ๐คทโโ๏ธ
Im not really asking for help to debug my code in specific, i am trying to understand how it works in unity with scriptable objects
hey there, assuming I'd like to make a rogue-like game with classes. would the best way to achieve this using a GameManager class that holds all the powerups (offered at the end of every level), the selected class, etc.? kind of a game state, I guess
I'd really like to see the bit where you declare your variables, for one. Like what access modifiers that _chestinventory has.
someone has to keep track of it
seems reasonable
so it wouldn't be an anti pattern to use it for that purpose?
most tutorials I've found regarding gamemanagers simply keep track of the game is paused and things like that. selected classes, powerups, etc. seems a bit more "higher" level
you can't get much higher level than a singleton game manager :p
I guess that it might be smarter to just have the player object hold the powerups
that would also make sense
When creating a 2D game, should i use multiple tilemaps to differentiate between layers?
yes, not a code question btw
For example, a tilemap for the ground layer, a tilemap for walls, a tilemap for objects ect
oh my bad, didn't see its code only
#๐ปโunity-talk next time ๐
can someone help me out with parent/child transforms? im having trouble with getting myhead around it
ill try to explain what im trying to do
i made this first using a single monobehaviour but decided to separate each wall segment into a separate prefab
and laying out tiles within the single wall segment works fine however im having trouble layout out the segments into a square afterwards
i thought applying a transform to the prefab itself would apply it to all children recusively however that isnt happening
using Assets.Prefabs.Wall;
using UnityEngine;
using Zenject;
public class WallBehaviour : MonoBehaviour
{
public GameObject Pivot;
public GameObject WallSegmentPrefab;
[Inject] private DiContainer diContainer;
[Inject] private IWallConfiguration wallConfiguration;
void Start()
{
for (int seg = 0; seg < wallConfiguration.SegCount; seg++)
{
var distanceFromCenter = -(Constants.TileHeight + Constants.TileWidth * (wallConfiguration.ColCount / 2.0f + 0.25f));
var wallSegment = this.diContainer.InstantiatePrefab(this.WallSegmentPrefab, Vector3.zero, Quaternion.identity, this.gameObject.transform);
wallSegment.transform.Translate(0, 0, distanceFromCenter);
wallSegment.transform.RotateAround(this.Pivot.transform.position, Vector3.up, seg * -90.0f);
}
}
}
using Assets.Prefabs.Wall;
using UnityEngine;
using Zenject;
public class WallSegmentBehaviour : MonoBehaviour
{
public GameObject TilePrefab;
[Inject] private DiContainer diContainer;
[Inject] private IWallConfiguration wallConfiguration;
void Start()
{
for (int col = 0; col < wallConfiguration.ColCount; col++)
for (int row = 0; row < wallConfiguration.RowCount; row++)
{
var tile = this.diContainer.InstantiatePrefab(this.TilePrefab, Vector3.zero, Quaternion.identity, this.gameObject.transform);
tile.transform.Translate(Constants.TileWidth * col, Constants.TileDepth * row, 0);
tile.transform.Translate(-(Constants.TileWidth * (wallConfiguration.ColCount - 1.0f) / 2.0f), Constants.TileDepth / 2.0f, 0);
}
}
}
specifically, these lines in WallBehaviour seem to have no effect:
wallSegment.transform.Translate(0, 0, distanceFromCenter);
wallSegment.transform.RotateAround(this.Pivot.transform.position, Vector3.up, seg * -90.0f);
which are supposed to move each segment away from center (defined by an empty Pivot GameObject placed in the center and rotate by multiples of 90 degrees
If your game manager is mostly just holding references and firing or subscribing to events, I think that sounds like a fine approach, though if your powerups are something that gets spawned in the scene, maybe it should be controlled by a "director" or "service" instead, if its just specific objects thats requesting powerups, it might make more sense to put those powerups in a ScriptableObject and reference it on the object(s) that need them - the game manager could keep track of a "game state" though (which could act similar to a state machine with classes as states or a simple enum if states act morel like checks over needing to execute any logic), for example, you could make the current state a property, and fire a event when the state changes, maybe some of those methods could work for your game
regarding my problem - it looks like the wall behaviour is executed completely before wall segment behaviours are instntiated
i assumed the code would be run synchronously
and that the InstantiatePrefab(wallSegmentPrefab) would execute WallSegmentPrefab's Start() method
im trying to figure out how to write a script for procedural mesh generation, my goal is to create a gridbased mesh just like the picture i added from a heightmap i could make in asperite. i think i can write a script so all the horizontal faces will be at the right position. i just cant find any resources on how to connect those faces with vertical faces https://gyazo.com/eb58b8bbcb8dfdaf2d135c17725dfe89
it would probably be easiest to just make cubes extended to the height they need to be at, but for performance and texturing i'd like it if it were a plane with extruded faces
what would be the best way to make a physics based update on the press of a button
cause in fixedUpdate the button isnt always registered
and in update the physics is varied by the framerate
i could make a variable thats activated but i feel like my code gets cluttered that way
already too cluttered
yo I have a dictionary of tiles with their key being it's position, defined as cs public Dictionary<Vector2, Tile> tiles;
I'm having an issue with this code:
if((MonstersSearching[i].Stamina <= 2 || OfflineResting[i])&& offlineSearchingDone[i]>0){
float decreasePerSecond = 50 / (Mathf.Log(MonstersSearching[i].AgiV / 100f, 4f) + 1f);
if(MonstersSearching[i].Resting){
MonstersSearching[i].Stamina += MonstersSearching[i].ConV * 0.01f;
offlineSearchingDone[i] -=decreasePerSecond;
OfflineResting[i] = true;
if(MonstersSearching[i].Stamina>=MonstersSearching[i].ConV){
OfflineResting[i] = false;
}
}
} else{
lootTable.SearchingCommon(MonstersSearching[i].Location);
int ForUncommon = Random.Range(1,61);
int ForRare = Random.Range(1,10001);
int ForRelic = Random.Range(1,1000001);
if(ForRelic == 1){
lootTable.SearchingRelic(MonstersSearching[i].Location);
}
if(ForRare == 1){
lootTable.SearchingRare(MonstersSearching[i].Location);
}
if(ForUncommon == 1){
lootTable.SearchingUncommon(MonstersSearching[i].Location);
}
MonstersSearching[i].Stamina -= 1;
offlineSearchingDone[i] -= 50;
} }```
the game will not load. if i remove MonstersSearching[i].Stamina -= 1; it loads fine. or it will run fine if i remove:
```if(MonstersSearching[i].Resting){
MonstersSearching[i].Stamina += MonstersSearching[i].ConV * 0.01f;
offlineSearchingDone[i] -=decreasePerSecond;
OfflineResting[i] = true;
if(MonstersSearching[i].Stamina>=MonstersSearching[i].ConV){
OfflineResting[i] = false;
}
}
} else{```
I dont understand why Stamina is causing issues.
whats a good way to find a 2x3 group of tiles where tile.isEmpty = true for all of them? (basically find a area of tiles that are empty?)
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
also probably you'll need to learn how to use the debugger
breakpoints will help you here
but i'm just gonna guess you have an infinite loop due to that while loop never finishing
i guess, i added breakpoints to notepad++ but they arent carrying over to unity. so ill probably need to install a new code viewer
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
and remember to configure it
everytime VS loads microsoft says invaild and kicks me out
invalid what
Hello all ! How can I change the alt negative button of my Input Manager via script ?
#๐ปโunity-talk message
and don't crosspost
I thought this channel might be more appropriate ^^
yo I have a dictionary of tiles with their key being it's position, defined as
public Dictionary<Vector2, Tile> tiles;```
what's a good way to find a 2x3 group of tiles where tile.isEmpty = true for all of them? (basically find a area of tiles that are empty?) i want to use it return a list of tiles where ill spawn the player.
I whould probly not use a dictionary for that. i think that a 2d array might work better where the index can be the postion instead and then the tile as the value
You should use Vector2Int not Vector2
Dictionary is a good idea if the data is sparse
As for the actual question just use a for loop
To check the 6 spots
but whould that not be harder as to check the postions in order or/and make sure they are next to each other needs alot more code and power
ah i thought just pick a spot, look at its neighbors in the relevant area and check them and if it fails pick a new one? but I'm not sure how to repeat it until it actually finds a valid option, or how to detect if there is no valid option and just make a new set of tiles
No it wouldn't be harder
To repeat code use a loop
If you check every coordinate and find nothing, time to make a new set
because you are using v2 instead of v2i the float discrepancies will produce errors in hashing
for a given corner, you see if any tiles exist in the corresponding 6 spaces
instead of v2 you should floor it into v2i so that the hash of (0.1,0.5) == (0.004, 0.999)
because both positions are in the same cell
oh yeah ill switch that, Ive been slowly switching the Verctor2s to V2Is in my script I just missed that one
There shouldn't be any need to floor things
depends heavily
if all the values are in positive space yes you can just cast
if it goes into negative youll get problems
It should all be in integer coordinates in the first place. The exception being maybe a query to check the coordinate of a mouse position or something
it was invalid license, i fixed it. trying to figure out how to debug now.
I want to randomize it not just find the first valid result so could it be a good idea to make a copy of _tiles, randomize it's order and then do a foreach loop on? exiting the loop once I find a valid position, and if i make it to the end without finding one making a new tileset?
anyway if you have a sparse set you can keep bounds or min/max and update it on inserts
so that you have at least known area or you can use each existing node in the set and keep visited set
so that you do the search around existing nodes
You could do that, sure
okay cool
You have to be careful not to make an infinite loop here
well im doing foreach, so it will eventually hit the end of the tiles,
at which point if we haven't already returned a list of tiles in the area I need, it will return null probobly and then what I'm calling this FindAreaOfTIles() will handle that accordingly
Right but you mentioned trying again if you don't find a legal space
What if that keeps happening?
i think ill just do a for each loop and break out of that loop with a return if I don't find a space, if I go through it all and don't ill just have it return null and then that will tell the game that there is none so it will then restart the grid making process instead of moving on to spawning the players in thoes tiles
Right:
restart the grid making process
Is what I'm worried about.
What if you restart the grid making process and there's again no legal spaces?
it would basically just do the whole process again,
it wont move forward in the logic unless I tell it to progress the gamestate
so it will keep looping untill eventually it works
and i mean technically theoretically it could repeated make invalid boards... ill add like a fail safe that throws an error if it runs like 100 times without working
i would just give up, destroy some tiles, and spawn the player :p
in fact, if the tiles aren't super well-structured (maybe they're just random junk in a field), you could use that as a spawning algorithm
carve out tiles to make room for whatever needs to be spawned
thank you, found the issue, i had 2 different rest methods, one was being set to true but the condition that was check wasnt being changed.
yo ive made it to this so far but how do i pull back out to the foreach loop?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Also, what do you mean "go back to the foreach loop", you are still in the loop. Do you mean continue?
continue wouldnt actually exit the inside for loops
you would need to add a bool then to exit those early. Or put your for loops inside a function and return early
Wrap it in a method and return, set a bool flag and check it on each iteration to fall out of loops or goto.
Could also set the iterators to the max value and continue
Or goto (which may have legitimate uses here, although I don't really like it) https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-goto-statement
acutally i think ill do that
u scare me
IK its not the best way
Yeah, setting h to areaHeight and calling break would escape the two loops.
but its simple and doesn't seem thaaaat bad...
Yea setting the iterators could have some side effects in loops where the outer loop does logic after the inner loop
honestly just putting it in a function is better, and looks cleaner so no one sees your n^3 loops
wow magic, my O(n^3) became O(n) by putting it in a function
computer scientists hate him!
so just throw the whole foreach loop into it's own method? or make a method replacing the inside of the foreach loop? with a method
void n2InnerLoop(Tile tile)
{
for(...)
{
for(...)
{
if(...)
return;
}
}
}
foreach(...)
{
n2InnerLoop(tile);
}```
Only the loops u wish to exit from
alr
{
recoil.DoRecoil();
audio.Play();
CameraRecoil.RecoilFire();
animator.SetTrigger("Shoot");
readyToShoot = false;
//find the hit position
Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); //ray that goes through the middle of the view
RaycastHit hit;
//check if ray hits something
Vector3 targetPoint;
if (Physics.Raycast(ray, out hit))
targetPoint = hit.point;
else
targetPoint = ray.GetPoint(75); //Just a point far away from the player
//calculate direction from the targetpoint to the attackpoint
Vector3 directionWithoutSpread = targetPoint - attackPoint.position;
//calculate spread
float x = Random.Range(-spread, spread);
float y = Random.Range(-spread, spread);
//get a new direction and add spread
Vector3 directionWithSpread = directionWithoutSpread + new Vector3(x, y, 0); //Just add spread to last direction
//Instantiate bullet/projectile
GameObject currentBullet = Instantiate(bullet, attackPoint.position, Quaternion.identity);
//Rotate bullet towards shoot direction
currentBullet.transform.forward = directionWithSpread.normalized;
//Add forces to bullet
currentBullet.GetComponent<Rigidbody>().AddForce(directionWithSpread.normalized * shootForce, ForceMode.Impulse);
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);
this is an annoying bugI've got a code that shoots/instantiates projectiles at a certain velocity from the barrel of a gun. they work fine but when i shoot too close to walls the bullets pretty much just don't work and dissapear and whenever i look down enough they shoot in exactly the opposite direction into the players face.
i tried fixing it but it wont work
Well, it can't just disappear.. where does it go?
so the bullet has a script attached to it
basically on collision it destroys itself
cuz it fires prefabs
So it immediately destroys itself. Sounds like a functioning behavior.
yeah but it never collides with the wall
What gives you that impression?
like you can shoot while standing in the door frame and if you go too close to the sides it 'collides'
Staying close to the wall implies it's going to hit the wall asap.
i can maybe send a video would that help
the more annoying bug is when i tilt down it shoots the opposite way
Log when it hits something and the thing it hits. Check if it's hitting the wall.
okay
also play it frame by frame assuming the bullet takes more than a frame to hit something
so u can see where it is
how?
either pause the game manually or insert a debug.break when u shoot so it pauses the game for u
im gonna record a quick video
try and debug what happens yourself given what we said first ๐
yeah
As for the floor, log the direction or debug a ray that'd illustrate the direction shot: cs Debug.DrawRay(attackPoint.position, directionWithSpread.normalized * shootForce, Color.red, 5f);
Okay thanks, I did what you said and wrote this line of code:
Debug.Log("the bullet has collided with" + collision.gameObject.name);
on collisionenter
(dont forget to turn on gizmos to see the debug ray)
Hmm, why did you apply a second set of force relative to camera up?
it claims to be colliding with the walls but its impossible
that code is mostly from a tutorial
That doesn't answer the question though 
wait lemme see
this?
currentBullet.GetComponent<Rigidbody>().AddForce(fpsCam.transform.up * upwardForce, ForceMode.Impulse);
The console never lies. Figure out why it thinks it did.
Well it confuses me because im standing in a doorframe and shooting at a target infront o fit
Should I send a quick video it can probably explain better than I could
whoops
im standing a doorframe
which i can walk through just fine
when i hug the sides
that just looks like ur colliders arent proper
Is there a collider there?
yeah its just a probuilder collider
Colliders could possibly stop the bullet.
You still haven't shown the log or the drawn ray.
sorry, the log says 'collided with arch (my walls)'
Also the bullet may not be spawning where we think it is, so draw some lines to show where the bullet spawns and its path. did u play frame by frame?
I sent a build to my friend for beta testing. Nothing fancy just a 2D game, the entire .zip is 22MB and has a .exe ... his Norton antivirus is blocking it, claiming "telepathy.dll is unsafe" and "Unity.Timeline.dll is unsafe" and so on and so on... what am I supposed to do so the builds don't get flagged by antivirus?
Debug.Log("the bullet has collided with" + collision.gameObject.name, collision.gameObject);```
Yeah, that's a thing. Unless you're rich or your application is popular.. your application will be receiving those messages for a while.
he would have to allow it in Norton
Also Norton is really really bad..
ignore that line 21 error its just complaining i disabled my enemy
it happens with enemy enabled too
Anything I can do on my side?
unless u put the game on steam, probably not
its possible for malware to exist in a game, antiviruses will check for it
highlight the actual collider for yourself too, its impossible for us to see where these rays are in 3D space because of depth perception
the player collider?
sorry if im being stupid
the wall it is colliding with
i see a single white line across the bottom, which would indicate to me that your bullet shouldnt pass through that at all
yeah, but i can pass through the door just fine
theres a few cases here,
- your wall collider doesnt exactly line up with the mesh
- the bullet doesnt spawn where its supposed to and is taking a path that looks like it goes through the entrance but doesnt.
- both cases above
- you have an extra collider somewhere
Not really. Here's a discussion on Reddit (it's also been discussed here many times but the posts are difficult to find) https://www.reddit.com/r/itchio/comments/tngwpd/my_game_is_blocked_by_windows_defender/
tldr, it's not worth your time or money to bypass this. Just hit the button to run anyways. Eventually it may be unflagged by defender - maybe.
and more that arent directly related to the collider
i'm gonna send another video rq
dont rely on me to look at your scene please. Im not gonna inspect your collider size and compare it to the bullet path
pause the game as soon as the bullet hits the wall maybe and debug everything to see whats really happening
Help...
Right, so there's a collider there.
your rays as well might be not accurate since i dont know what u wrote. Your rays might be showing the intended path but the bullet mightve not taken that entire path
yeah ur right
im getting this error, its in the third person starter assets pack: 'PlayerArmature' AnimationEvent 'OnLand' on animation 'JumpLand' has no receiver! Are you missing a component?
Your animation JumpLand has an animation event calling OnLand but there's nothing for it to target.
Okay well I've just figured something out
any glaring issues?
u tell us, does it work?
I think it's just my probuilder colliders are terrible
because i made a doorframe out of box colliders with blocks and it worked fine
fine I was just asking here cuz i have to do some other stuff to implement it
fixed it
thanks
Okay well i've fixed my doorframe collider issue by just messing with the bullet's rigidbody somehow but there is still the issue of whenver i look down the bullet fires in the exact opposite direction and even the rays just show it like completely firing from the attackpoint the opposite way it's supposed to
a rigidbody alone shouldnt have done much... but im glad it worked
that might be if it collides with the player hand/gun/floor/anything when it spawns, it might instantly bounce back. Unless u have it destroy on any collision at all
Log your target point, attack point position and camera point.
The resulting direction would be the result of those two.
well idk i just tried disabling the rigidbody on the bullet, broke the code so i enabled it again, made it kinematic to see what it'd do, it broke again so i reenabled everything and it fixed itself..
If origin is below target (you're shooting from the camera and not the attack point with the ray check) the shot would be in the opposite direction.
yeah its meant to just shoot to the middle of the screen
thats what the ray is for
but i'll do that rq
Okay I aimed all the way down
target point pos (4.60, 2.37, 10.65)
attack point pos (4.76, 1.71, 10.99)
So the target is above the attack point.
Meaning you'll be shooting up.
target - attack = direction
right
This is occurring because the initial raycast is from camera and not the attack point.
After determining the point of collision relative to the camera, use a ray generated from the attack point as the actual shot ray.
Wait.. I believe that's what you did.
Issue is the attack point is below the expected collision.
ie your gun is through the floor etc
I thought so too at the beginning but it isn't
Depends if you're wanting to shoot through the floor or whatnot, you'll need to implement a feature for dealing with shots where your gun (attack point) is through the floor or below the collision point.
yeah
Basically camera sees the collision point above the attack point so shots are being fired towards yourself.
You may be hitting other things such as your lower body with the initial contact point though - only you'll be able to determine this with debugging.
If that were to happen the bullet would just destroy itself
the rays show that it just goes the opposite way
Bullet shouldn't be able to hit itself. Check what you've hit when shooting down.
The log would tell.
It doesn't hit anything as it just shoots into the sky
if (Physics.Raycast(ray, out hit))
{
Debug.Log($"Camera ray hit: '{hit.collider}' at point {hit.point}");
targetPoint = hit.point;
}
else
targetPoint = ray.GetPoint(75); //Just a point far away from the player```
what the hell is that ?
Should not be capturing when there is a hotcontrol
UnityEditor.EditorGUILayout:PropertyField (UnityEditor.SerializedProperty,UnityEngine.GUILayoutOption[])
should i ignore it ?
Editor question, maybe ask #โ๏ธโeditor-extensions if it's true (are you doing something with the Editor and serialization?)
oh yeah i'm , i have a custom editor, i think it's gone for now , maybe it was a glitch or something
but thanks a lot for the support โค๏ธ โค๏ธ
You'll know if it's related or not
Basically:
This can be reproduced with the steps listed at https://issuetracker.unity3d.com/issues/should-not-be-capturing-when-there-is-a-hotcontrol-message-thrown-after-double-clicking-on-runtime-error-and-exiting-playmode
The specific issue is marked as "Resolved", but still appears in the latest version of Unity (As you have seen)
I think ill be taking your advice, before I was reluctant because did not feel like making a way to change a tile live, but its probably something I should have anyway so might anyway
lmao i wonder if one day someone will play it and get a map thats litterally entirely unwalkable besides where the players spawn, and a path to the enemies(which i will also be checking for making sure exists)
i suppose there are two ways to produce a level
one is to generate features, and then subtract the ones that get in the way
the other is to figure out what areas can be filled in, and then generate features in them
So I am having an issue of compile times. I am using assemblies, but it is taking 1-2min everytime I save a change to a scripts, and that combined with 1-2min to get into play mode is a killer on productivity. The playmode I have fixed by using a test scene, but the compile time is still there.
My assemblies have like 50+ scripts each, so maybe time to split them down some more? Can you have sub assemblies?
Also is there a setting to stop unity from compiling while I am in VS?
Cool, because if I am creating a new script it makes sense to reload after each change, but I am currently just cleaning code up, and it is eating so much of my time lol
i wish i could tell it to hold off while I'm moving scripts around
indeed
what's the best way to implement a hit stop on say a per hit basis? Should it simply be a global timescale set to 0 for a short period of time or something else?
that's what I've done in the past
a very short period of 0 timescale
some effects may need to then be set to use unscaled time
e.g. a camera shake during the stop
eye sea
also, if you do this in a coroutine, make sure to use WaitForSecondsRealtime ๐
is there a way to change the position of a sprite renderer component relative to the gameobject it is attached to?
change its localPosition instead of position
or rather, make it a child of the gameobject and do so
that still changes the position of the gameobject in world, not the component itself
i need the sprite renderer to be attached to a gameobject but be visually at a different location than the gameobject itself. I can't attach it to another child gameobject
is this actually not a code question but rather a "my sprite isn't in the right position when i add it to the gameobject" question? because that would just be changing the pivot point of the sprite
no I need to update it at runtime to be at a slightly different position than the actual gameobject it is attached to for pixel snapping purposes
Change the pivot point of the sprite
but if I change the position of the actual gameobject it leads to desyncing between the gameobject with the sprite renderer component attached whenever sub-pixel motion occurs
can the pivot be updated at runtime?
it isn't letting me set it, according to rider it only has a getter
I'm just trying to set it to a random offset here for testing purposes
Well that's annoyingly undocumented
yeah i went and look and the docs don't show it as readonly, but it definitely is https://github.com/Unity-Technologies/UnityCsReference/blob/4b436cf82aaff7a0719e373ee8af4f4625f05638/Runtime/2D/Common/ScriptBindings/Sprites.bindings.cs#L134
yeah it is lol
Options then are:
- create a new sprite with a different Pivot
- try to change it with reflection
- move the GameObject
been searching the documentation for something I can use that isn't readonly
perhaps I'll have to do it at a rendering level
which will not be fun
because it needs to be sprite-agnostic
https://docs.unity3d.com/ScriptReference/Sprite-textureRectOffset.html maybe? I'm not sure what's different about this vs the pivot
moving the gameObject leads to the desyncing issue
sadly this is also readonly
I'm not sure I understand the desync issue but I'll take your word for it
basically if I move the gameobject the spriterenderer's gameobject is parented to, any subpixel-motion doesn't apply and so if you move in sub-pixel intervals over time it will desync
whoops sorry hit enter early
and this needs to support non-zero offsets of the child gameobject with the spriterenderer to the parent gameobject
so I can't just use the parent gameObject's position value to calculate the new snapped value
I guess theoretically I could introduce a third gameobject into the mix
it's not elegant but it might work until I can get under the hood and figure out if I can offset it at some point in the render pipeline
that would require any motion applied to the gameObject to be done to the subPixel Vector3 rather than the object's transform
which is something i'd like to avoid
as this is meant to be a project-agnostic system
Apply whole number motion to the GO and the remainder to your variable
And when the variable accumulates a whole numbers worth you consume that
you can probably store them as a Func<IEnumerator> so that you don't start executing any of the coroutine's code until you Dequeue and then invoke it in the StartCoroutine call. I haven't tested this though
this worked, thank you so much!
just tested, this is the way to do it. @wide fiber
This definitely looks like a valid collision, right?
I'm not sure why, but it's just not getting registered
How are you moving the axe?
an animation
oh i think i know what's going on
I'm using OnTriggerExit
but sometimes due to the way the animation works
the axe's mesh collider is actually disabled before it leaves the player's collider
and so the call is never made
I would probably just use physics queries for melee weapons
ok i will try this! thank you!!
any chance would anyone know why the ui on my hotbar is broken on the second client? its multiplayer and im using mirror, the UI recognizes there is an object there just the sprite doesnt load
What object? And how do you load the sprite?
the sprites is loaded from a scriptable object
this is the second client
this is the first
So what's exactly not loaded?๐ค
Also there seem to be 7 errors in the first screenshot
there just misc errors unrelated, (footstep audio)
in the first pic if you look at the hotbar
the sprite isnt there
Where do you add items to the hotbar?
hii, can we put collider-related questions here?
the bottom row corealates to the hotbar so what ever item is in there the will show in the hotbar
its drag and drop
If they're not code related, then : #โ๏ธโphysics
thanks โค๏ธ
I mean, in code...
wait
ill upload to a file for easier readibilty
what website can i upload it to
i forgot what its called
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Ummm... Wat? Where is that even called from?
thats called everytime theres a ui change
If you share code, please provide the whole context. If you can't decide what's related, share the whole script.
Don't just copy-paste part of a method.
one sec ill share the whole script but you did ask where i added objects to the hotbar
Ok, for starters, don't use try catch to handle your ui logic...๐
alrighty noted ๐ haha
Add debugs along your code. Make sure your refresh ui methods is even being called.
If it is, then your try catch is probably catching some kind of error. Remove the try catch and instead make proper null checks. Add debugs there as well.
And fix the other errors or disable the code that generates them. You don't want to go through a bunch of errors looking for the right one...
It's blasphemy to keep errors in your console without addressing them.
the error is because the footstep audio isnt networked haha so its getting a null reference
Then disable the relevant code.
Or are you planing to publish your game with these errors?
It doesn't matter what causes the errors. It's not normal to just ignore them.
nah i was just going to fix it later as it isnt game break
its in my trello todo list for misc stuff to fix
Well, it might get in your way of solving other issues. But suit yourself
i got rid of the try catch and added a null check but that still didnt solve the issue unfortunatly
ive just disabled the relavant code for that
so ill just fix the footstep audio at another date
Well, what happens now? Are there errors? Share the updated code.
no errors and the updated code is https://gdl.space/wedutadoxa.cs
i tried with 3 clients the sprite only shows on 1
Ok, that could only mean that
items[_index].GetItem()
of the right slot(assuming it's right) is null.
Add debugs along your code as I suggested before to know if anything before that stage is going wrong.
Look at where you're adding the items to the slots and makes sure there's no problem there.
Yeah the hotbar item is null
Great. Now figure out why it's null. Probably because you're not setting it.
In the previous week unity made a change in remote config and it messed up all my project,
I added obselete to configManager still didn't work
I also replaced unity.remoteConfig to unity.services.remoteConfig
And configManager to RemoteConfigService.instance
Still no luck
Am I missing something????
i have an object that needs to overlap sphere around it every update. should i add another collider with a trigger for that? but then the radius and later shape to check will change. right now i have a script that overlaps sphere and filters through the returned array, but it's sloppy.
Are you asking if overlap is more performative than using colliders*?
Technically, a collider will do similar checking over an array with all other colliders in the vicinity, so what you're doing isn't exactly that different from just using a collider. One plus of checking with overlap, you get to control how much it checks for colliders instead of every (fixed?) update.
Of course if the game object is small or traveling quickly, you'll want to check as much as possible.
Hey good day.
I have this code:
public static IEnumerator BacktrackerRecursivo(Celda[,] laberinto)
{
// Stuff
while (pilaVisitados.Count > 0)
{
if (GeneradorLaberinto.EjecuccionPorPresion)
{
while (!GeneradorLaberinto.EjecutarUnaVez)
yield return null;
GeneradorLaberinto.EjecutarUnaVez = false;
}
else
yield return new WaitForSeconds(0.5f);
// Stuff
}
}
This code does stuff but waits for the user to press a key (the condition in the while) before doing each iteration of the while.
I want to know if i can make that if-else into a function becouse i have it repeated in more than 1 method
Any advice?
Hi guys,if when i spawn a prefab when game starts i want that when this prefab click a button call a method contained in a script attached at an object in the hiearchy that is there since before the game starts how can i do it?
Stop cross posting.
is there any way to render a tool (eg a gun) so that it doesnt mesh into walls, but at the same time isnt see-through
i used the method where you render it on a seperate camera ontop of the main camera, it worked but theres the issue of the tool being see through
Is that the perspective of your game?
The dual camera method makes sense for a first person game, not so much for this kinda game
oh
I'm not sure what you want it to look like though
it meshes like this
So you want to render it on top of walls, but not be seen thru walls
Thats contradictory
How would you make a corrutine wait until the player press a key before continuing?
Like the function does stuff then waits for a key press before continuing doing stuff
yield return new WaitUntil(() => Input.GetKeyDown("space"));
IEnumerator Dialogue(string[] texts)
{
var wait = new WaitUntil(() => Input.anyKeyDown);
foreach(var text in texts)
{
ui.text = text;
yield return wait;
}
}```example
This get executes 2 times per presion
What is a presion?
When you press space i mean
What happens then?
Two executions of the stuff that should happen once
You'll need to provide more context to get better help
well you have the coroutine running twice then
Okay i will explain more, sorry for the confusion
you missing the > from that () = Input.. ?
Coding using a mobile keyboard isn't so fun.
I have a maze and im making corrutines to be able to show the process of making the empty maze into a proper maze using algorithms.
To do so i have decided to make the algorithm a corrutine and make the iterations of said algorithm wait until the user press space to do a iteration (like, you press space and a cell fo the maze gets build)
I have this code:
public static IEnumerator BacktrackerRecursivo(Celda[,] laberinto, Vector2Int posicionInicial)
{
// Stuff
while (pilaVisitados.Count > 0)
{
posicionActual = pilaVisitados.Peek();
laberinto[posicionActual.x, posicionActual.y].EstadoActual = EstadoCeldaEnum.Actual;
if (GeneradorLaberinto.EjecuccionPorPresion)
{
while (!GeneradorLaberinto.EjecutarUnaVez)
yield return null;
GeneradorLaberinto.EjecutarUnaVez = false;
}
else
yield return new WaitForSeconds(0.5f);
// Stuff
}
}
This works more or less. I can translate if needed but the variables are a static variable to make it execute just once and a condition to see if it must be execute by waiting 0.5 secs or by presing space
It's how the pr0s do it ๐
Which IJob interface does your struct implement?
The IJob
The Schedule method is an extension method under the Unity.Jobs namespace.
IDK what to say, I have using Unity.Jobs
It's definitely in 2021.3. So either you're implementing the wrong interface that also has the name IJob, or your IDE is wrong and it will compile in Unity.
show your code
[BurstCompile]
private class FindNearestFoodJob : IJob {
private readonly Vector3[] _foodPositions;
private readonly Vector3 _headPosition;
private NativeArray<Vector3> _nearestTarget;
public FindNearestFoodJob(Vector3[] foodPositions, Vector3 headPosition, NativeArray<Vector3> nearestTarget) {
_foodPositions = foodPositions;
_headPosition = headPosition;
_nearestTarget = nearestTarget;
}
public void Execute() {
float sqr = float.MaxValue;
foreach (var foodPosition in _foodPositions)
{
float distSqr = (foodPosition - _headPosition).sqrMagnitude;
if (distSqr < sqr)
{
sqr = distSqr;
_nearestTarget[0] = foodPosition;
}
}
}
}```
var job = new FindNearestFoodJob(foodPositions, headPosition, _nearestTargetNative);
_jobHandle = job.Schedule();```
Your job is a class, not a struct.
yeah, I thought that looked a little funny
Also, you can't use managed arrays in jobs. You have to use NativeArray
Should it be like this instead?
var job = new FindNearestFoodJob(new NativeArray<Vector3>(foodPositions, Allocator.Temp), headPosition, _nearestTargetNative);```
That will introduce a memory leak because you're not disposing the array.
Should I dispose of it at the end of the job? (inside)
I don't think that's possible in a job(that would be on the other thread)
Where do I do it then?
Create a local variable outside the job and dispose of it later when getting the results of the job.
Doesn't have to be local I guess
Should I Dispose of it right before giving it a new value then?
That's one option, but I think unity would be angry at you if you keep it alive for several frames.
Could be mixing up with something else๐ค
Gonna try
You also need to use TempJob or Persistent if you want to pass it into a job.
Okay, thanks
sigh im back again :/ i seriously want to off my self, i found out the root problem of my problem earlier and its because the inventory isnt synced up with the server
but idk how to sync it, i cant find any decent references
Well, that's more of a #archived-networking question.
You'd either user rpcs or some kind of synced properties to sync data between server and the clients.
i want the inventory to be server authorative but again i cant find a single reference ๐ญ
Have you tried serializing it with INetworkSerializable?
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/inetworkserializable
im using mirror haha
Server authoritive means that the logic is controlled on the server and the client only displays the visuals. Shouldn't be too difficult.
If you can't figure it out, maybe it's too early for networking..?
i dont really see any other way to learn than to try it, its just i cant find anything usefull that i can learn off
my team uses a chaotic setup for backends
cant recommend that to u , it gonna ruin ur game
somehow it works tho
Learn more general cases of syncing data between server and the client and apply it to your specific case.
Back when I used Mirror I used BinaryFormatter to convert data into a byte array, and then sent the data as byte array via ClientRPC. It's not comfy, but it did the job. ๐ค But it's recommended to avoid BinaryFormatter.
what would you recommend for differnet cases for syncing data between server and client?
i want to move to fishnet so bad but im somewhat familiar with mirror i feel like migrating would be utter aids
theres more reference material for fishnet to learn off
https://www.youtube.com/watch?v=b7urNgLPJiQ
theres already some tutorials showing how to breakdown binary formatter stuff
โถ๏ธ YouTube: https://www.youtube.com/c/PinkDraconian
๐ Patreon: https://www.patreon.com/PinkDraconian
๐ฆ Twitter: https://twitter.com/PinkDraconian
๐ต TikTok: https://www.tiktok.com/@pinkdraconian
โน๏ธ LinkedIn: https://www.linkedin.com/in/robbe-van-roey-365666195/
๐ Discord: PinkDraconian#9907
๐ท Instagram: https://www.instagram.com/robbevanroey/
๐ธ๏ธ ...
ive heard of this Binary exp
welp, only use it if u know what ur doing
and u have the confidence it wont bring ddos or other bad stuff to ur server
cant you restrict the amount of data being formatted? so it doesnt cause dos ?
fuck i need sleep :/
but i wanna finish :/
Here is some example of syncing variables on clients:
https://www.youtube.com/watch?v=COLp1PzPKvE
This user has a whole series of Mirror tutorials.
Anything. Movement, log in information, etc...
i will look into it
Hello there, having some thoughts right now on how should i implement my "Game manager script".
Should i :
- Make a static class "GameManager" which is never linked to a GameObject and accessed globaly through the engine ?
- Make a "GameManager" MonoBehaviour, instantiated in a preload scene, accessed through singleton throughout the game ?
- Make a "SpecificSceneManager" MonoBehaviour, instantiated in each scene, accessed only during the specific scene i am and destroy by switching scenes (which are used as "states")
Somehow, the [2] options seems the best choice to me
i would personally choose singleton but some people have have there problems with singletons
I usually just make a component that makes itself available via a static field
If it needs to survive between scenes, it would get marked DontDestroyOnLoad()
Were you there 3 min ago ๐คฃ
one suggestion: do it more like this
It kinda depends on what your manager does. Instances of managers are handy in multiplayer games (e.g. you can have a separate manager for every match instance). I suppose instances also could be handy if you wanted the possibility of having several instances accessible at the same time, kinda like tabs in a web browser or project files in Photoshop.
If you're 100% sure you're never gonna need it duplicated, then any solution will do.
MonoBehaviour managers are quite handy if you want to configure them or debug their values in the inspector.
public class GameController : MonoBehaviour {
private static GameController _instance;
public static GameController Instance {
get {
if (_instance == null) {
_instance = FindObjectOfType<GameController>();
}
return _instance;
}
}
}
this lazily initializes the singleton
this is useful if you want to have other things find this guy in their own Awake methods
if you do it this way, I'd suggest also checking that Instance == null
if it isn't, log a warning that you have two GameControllers
Thanks for your reply !
Thanks for your reply !
Howdy all! I'm trying to remove a outline on a Instantiated object but it's not working. Can anyone spot what I'm doing wrong?
GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel);
Outline removeOutline = buildedItem.GetComponent<Outline>();
removeOutline.OutlineWidth = 0f;
Thanks for your reply !
is it throwing an error?
is this some kind of custom component? I don't reecognize it
i would do
public static GameController instance;
private void Awake() {
if(instance == null) {
instance = this;
} else {
Destroy(this);
}
}
so you know its only initalized 1 time
Yeah it's a asset, it works when I use it on BuildingMenuItem.newItemModel but I want to remove it only on the Instantiated object
i just completely removed mirror from my project and un networked all my scripts and im going to migrate to fishnet as it seems more reliable
Why are you using FindObjectOfType to find the type that contains the literal property? You can just do _instance = this
this is a static method
it is a lazily-initialized property
why the snake case tho
it's a convention for private fields
Also, talking aobut improving the system, I suggest you make sure that there's not multiple instances of the given type
private field
ah yes
Ah right, this was an alternative instead of doing it in Awake
ya
There's not a whole lot of reason to lazily initialize it, though
it's a little more code, but it completely avoids problems with ordering
whats wrong with just doing what i said tho haha
Nothing really
yeah, it's fine
we're bikeshedding here :p
you probably shouldn't have singletons trying to talk to each other in Awake
fair enough was just wondering haha if theres anything wrong with that lol thats how i normally do it
so it wouldn't come up anyway
This lazy initialization sounds like a good way of avoiding blockers in build, but I would suggest adding a warning log to it so developers will know there were some issues with the initialization order and patch it up later.
Do you make a difference between game modes and game states ? Or do you implement both using FSM ?
Honestly, it's hard to tell. I suppose in some cases I would go for completely independent scripts and sometimes I would use some kind of FSM. FSM would be great if you can't simply turn off the other game modes, which would allow the player to choose what mode he is using right now (e.g. in the pause menu he shouldn't be able to interact with his game except resuming the game, and during the game, he shouldn't be able to interact with pause menu except entering it, but there is a chance both things will be active at the same time). I suppose FSM would work well for implementing mini-games and such. But there is no need for FSM if every game state is separatable beings, such as levels in games (you can't be at the 2 levels at once).
Still nobody that can help? #archived-code-general message
what is the asset you are using
cant u just destroy the Outline component as a whole instead of setting it to 0
Did you try to disable the outline Component 'removeOutline.enabled = false' ?
It doesn't destroy the outline :S
GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel);
var removeOutline = buildedItem.GetComponent<Outline>();
Destroy(removeOutline);
Doesn't work either
i dont know then
The is a outline mode hidden
set is outline mode
Well the thing is all code should work but somehow the GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel); looks like it's not defining the buildedItem
If I use it on BuildingMenuItem.newItemModel it's all working
But I only want to target the Instantiated object
BuildingMenuItem is a static class I assume?
yes
yeah makes sense it'd do it for all objects then... hmm
maybe u need to add your own custom func to the Outline script to make it happen
But it should still be possible to destroy the outline component on the Instantiated object right? :S
Anyone here who has ever used Runtime Hierarchy and Inspector? I am having a problem that the text in hierarchy and inspector is not visible anymore when I play my game. Why am I using it? Because I am making an AR game which can't be debugged in editor while playing.
yes but if i understand what youre saying correctly, you already tried that and it didnt work
Yes indeed very weird
what is this BuildingMenuItem class
It holds the prefab that is selected to build
is it your own class or did it come with the asset
my own
is buildedItem actually the obj that holds the outline comp? are u sure
like not a child of that obj or smthn
Using FinalIK, some asset from the store, I'm running into issues manually controlling the execution order of the solvers.
In my tests, by accident, I realized that disabling and re-enabling the actual solver components in the order than I want will cause them to execute in that precise order.
I was able to confirm the behaviour with the simple class below. I added 5 instances, enabled them in the order I want and their update order will follow the order in which they were enabled.
e.g.
public class PrintFoo : MonoBehaviour
{
[SerializeField]
private string foo;
private void Update() => print(foo);
}```
Does anybody know if this behaviour can be relied upon? Will this be persistent across platforms?
buildedItem is the Instantiated of BuildingMenuItem.newItemModel which should hold the outline component
first time I try to target a Instantiated object
it should* but does it? need to be certain
I assume so else the outline wouldn't work I think
does buildeditem have any children
The outline stays active so
?
GameObject buildedItem = Instantiate(BuildingMenuItem.newItemModel);
that doesnt rly answer my question
youre instantiating a prefab
a prefab can have children
can u show me ur buildedItem prefab in the editor
oke no children
I now see the Outline component isn't part of the prefab, but get's added to it when I click the menuItem
i think i see
but I think that still wouldn't be the problem?
i think it's editing the material and setting it once
meaning, the material is permanently edited
meaning removing the component wont do anything as it already fulfilled its task
is there any way you could confirm this theory?
Yeah I can check if the component gets deleted
it would have been a problem if the component was on a child, bcs then it wouldnt have been gotten with GetComponent and thus wouldnt do anything
nah im sure that happens. thats fine
i just think that the material is edited
so removing the component after its been edited wont do anything
u need to find a way to revert the material to its original
maybe u can save a duplicate?
do keep in mind that it shouldnt have the same reference, because the material doesnt get changed per-object.
confirmed
it gets changed in its root, so it applies to all objects with that material
ahhh
its its own material
thats good actually
u should try grabbing the outline fill and mask materials and remove them from the object
if u just manually delete them at runtime, does the outline disappear? if so, then we've found the root of the problem
hmm well try to remove those materials with code and i think you should have your solution
List<Material> myMaterials = GetComponent<Renderer>().materials.ToList(); and then the first 2 i assume
u may need to refresh something afterward to clean up or smthn
My question is about Unity Matchmaker. I want to have rival's name when matchmaker responses match id( also ip/port) to each client. I'm using photon fusion and transfer names by using RPC's. But it is too slow to transfer names. I need to show rival's name before being connected to photon. Thanks.
List<Material> myMaterials = buildedItem.GetComponent<Renderer>().materials.ToList();
Debug.Log(myMaterials);
like this? sorry also first time to target materials
The code above gives this error: error CS1061: 'Material[]' does not contain a definition for 'ToList' and no accessible extension method 'ToList' accepting a first argument of type 'Material[]' could be found (are you missing a using directive or an assembly reference?)
ToList is an extension method added by System.Linq
How can I combine the Asstes, https://assetstore.unity.com/packages/3d/animations/low-poly-animated-modern-guns-pack-urp-234191 with https://assetstore.unity.com/packages/tools/animation/fps-animation-framework-238641
what is this a screenshot of?
Android logcat when i run my unity app
It fires them like every second
Okay now I get System.Collections.Generic.List1[UnityEngine.Material]
UnityEngine.Debug:Log (object)
GridController:Update () (at Assets/Scripts/GridController.cs:68)`
the ToString method for a list just spits out the type
How can I delete/target elements from it now?
List has a Remove method that allows you to pass an item inside the list to be removed
Are you sure it's even related to your app?
Alternatively find it using First/Single/FirstOrDefault/SingleOrDefault/Where, and then use Remove.
Depending on the method you need to handle it differently.
myMaterials.RemoveAll(x => x.name == "OutlineMask (Instance) (Instance)"); doesn't work, how should I target the elements?
List<Material> myMaterials = buildedItem.GetComponent<Renderer>().materials.ToList();
foreach (var x in myMaterials)
{
if(x.ToString() == "OutlineMask (Instance) (Instance) (UnityEngine.Material)")
{
Destroy(x);
}
if (x.ToString() == "OutlineFill (Instance) (Instance) (UnityEngine.Material)")
{
Destroy(x);
}
}
Fixed it, thanks all for the help! โ๏ธ
that's a little scary...
you probably just want to check which shader the material has
Material mat = // ...
mat.shader == shaderField;
where shaderField is a field of type Shader
you would assign the shader you want to get rid of
I have a "Task" object in an synchronized method.
How can i wait for the task to finish? Theres no callback
Material mat = // ... ??
mat = x ?
just get the material from somewhere
was just an example of what you could do
in this case, yes, x is a Material
Anyone?
How do i define shaders?
Yeah that i get but
Shader check1 = Custom/Outline Fill;
you can't just write a name like that
public Shader shader will create a field
you can then assign a shader to that field.
Aaah
I do believe you can look up a shader by name, but you might as well just assign a reference so that it's guaranteed to be right.
The fuck
I mean, there's probably a better way to check the stuff to remove than their name
This just screams prone to error
that's why we're having the current conversation
bonus: you'll be able to write it like this
var materialsToDestroy = buildedItem.GetComponent<Renderer>().materials.Where(x => x.shader == shaderToDestroy)
foreach (var mat in materialsToDestroy) {
Destroy(mat);
}
although, this seems a little odd
destroying the materials instead of just, say, assigning null into the material slots
I guess it works out the same. materials will make unique copies of the materials for that specific renderer
so destroying them won't affect anything else
note the lack of ToList -- you do not need to explicitly turn that sequence into a list if you're just gonna iterate over it once anyway
I have a settings menu in my game (two separate ones: one for the pause menu and one from the main menu) that can control volume and a few other gameplay settings. What's the best way to handle this? Right now, I have a Settings class that is a singleton and works as a place to store current values so I can reference it from different game objects to use those values. I feel like there's a more conventional method, though..
sounds reasonable to me!
var materialsToDestroy = buildedItem.GetComponent<Renderer>().materials.Where(x => x.shader == checkOutlineFill || x.shader == checkOutlineMask);
foreach (var mat in materialsToDestroy)
{
Destroy(mat);
}
it is ๐ช
tada
bit of a long line
one way to improve that is to put line breaks before the Where
foo.GetThings()
.DoStuff()
.DoMoreStuff()
.Microwave();
this is a common pattern when using LINQ
each operation gets its own line
Epic stuff! Thanks for all the help and explanation buddy! ๐ช ๐
no prob
Any idea why those artifacts are occuring?
Doesn't look like a coding question but ensure that the normals are correct.
Non coding questions should be asked in #๐ปโunity-talk or it's specific channel #๐โfind-a-channel
hi, i have an isometric tilemap and am trying to allow the user to hover over the tiles and click to select them. however, i have a problem where the tile that my cursor is on is not actually the one that is being selected when i hover. the image shows an example, where the red is the cursor.
// Get the mouse position in world coordinates
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int tilePos = world.WorldToCell(mousePosition);
tilePos.z = tileZ;
// Try to get a tile from cell position
TileBase tile = world.GetTile(tilePos);
here is the code i am using to get the tile that is being hovered over. this code is in LateUpdate. is there an issue here?
are you sure the Z is correct?
oh perhaps it is not, let me check give me one second
actually just to make sure, how would i make sure the z is correct
I think you can see it in the tilemap
hmm where in the tilemap? here is a ss of what i see
and here is the inspector
it should be on grid, what did you set yours too ? I see it's a variable
hmm yeah 0 should work..
that Z as Y though is sus that could be it maybe, I never used ISO before just hex/squares
hmm maybe, ill try making it a not z as y tilemap and then see what happens
nice that fixed it
thanks @rigid island now its time to figure out why that might have fixed it by first figuring out what z as y means
time to spend hours reading unity docs!
just the way it's laying out the tiles I guess in respect to unity's world coords
hmm yeah but im not sure what Z as Y means in particular
like i understand that its taking whatever Z is and somehow putting that information in the Y coord, but i dont know how it does that...
ahh
https://gamedev.stackexchange.com/questions/200515/trying-to-get-sprite-from-isometric-z-as-y-tilemap
interesting reads here too, not sure it relates
in this case is y the vertical axis? like its going up and down?
ahh 2d hella confusing xD
i remember the pain of figuring that out with hex tiles, i had to change sort axis into some weird number. It was not fun xD
tilemap itself is easy tho
yeahh -0.26 lol they are pulling numbers out of their ass
magic numbers xD
i presume the value depends on the view angle
lmao thank you though, at least i know what makes it work so that i can figure out the rest of the details
yeah, likely
I'm working on a 3d tilemap as well. For me on the grid Z becomes Y
but everything I place on top just uses the normal cords
But I'm also really utilise the 3d space and models, don't know if you have it same or you are just using 2d that looks 3d?
yeahh so i ended up using normal iso instead of z as y iso, party because i also want stacked tiles to have different z values because in my game only the bottom most tiles can be selected as i had in my question above
but yes i am just using 2d that looks like 3d
I would say if you want to stack, use multiple grid layers
i am using a 2d tilemap, i am not making 3d models and fixing the view as isometric with the camera
yeah good idea
is this what ur doing
why is my sphere not sticking: ```private void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag("Stickable"))
{
transform.parent = collision.transform;
Debug.Log("sticked");
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.collider.CompareTag("Stickable"))
{
transform.parent = null;
Debug.Log("unsticked");
}
}```
do your logs get printed
Do both objects have colliders? Does any object has non-kinematic Rigidbody?
foreach (ContactPoint c in playerRigidbody.GetComponent<Collider>().contacts)
error CS1061: 'Collider' does not contain a definition for 'contacts' and no accessible extension method 'contacts' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)
That line of code cannot report that error
Ah, better
Contacts can only be fetched from collision callbacks like OnCollisionEnter. Colliders themselves don't have such knowledge of contact points
i try to implement a mechanic
where a player can stick on a bigger sphere which rotates
and if you push spacebar you jump and you can move free again, no gravity.
working on a full body fps character, what methods are used to keep the camera from shaking around with an animation while parented to the characterโs head?
@simple egret you know why my player keeps bouncing?
{
if (isSticking)
{
// Set velocity to zero
playerRigidbody.velocity = Vector3.zero;
// Calculate the offset based on the size of the sticky object's collider
Vector3 offset = stickyObject.GetComponent<Collider>().bounds.extents.y * Vector3.up;
// Calculate the player's position relative to the sticky object's rotation
Vector3 relativePosition = Quaternion.Inverse(stickyObject.rotation) * (transform.position - stickyObject.position);
// Set the player's position to be just above the sticky object, taking into account the sticky object's rotation
transform.position = stickyObject.position + stickyObject.rotation * (relativePosition + offset);
// Disable the player's rigidbody gravity and velocity
playerRigidbody.useGravity = false;
playerRigidbody.velocity = Vector3.zero;
}
else
{
// Enable the player's rigidbody gravity
playerRigidbody.useGravity = true;
}
}```
Ah that's a question
The lack of ? at the end of the sentence made me doubt
Anyway, you should not ping specific people into your question as it's a brand new one here
my bad thought you were already answering my previous one
The previous one yes, that one is a new one
But no, I don't know why it bounces. Is execution even reaching into that if statement there? Where you set .velocity = Vector3.zero
Canceling out the velocity should probably be done in OnCollisionEnter so it's as fast as possible
Does anyone know why the ConcurrentBag.Clear method is not showing up in my Class Library within Visual Studio? I have my Target Framework set to 4.8. If I create a script within Unity the Clear method shows up. Just not in the external class library . . .
Nevermind, I guess the frameworks do not have support for the Clear method. I guess I misunderstood the frameworks. I thought you got Standard 2.0 (or 2.1) support plus more features with them, but it looks like Standard actually includes features that the frameworks don't?
That may depend on how your character is setup, but generally, you either want to control the position and rotation by code, or attach your camera separate from your bone rig, for example, this is how ive setup mine - the "node" is a container that holds scripts like input, movement, etc but it doesnt move itself, "root" contains colliders and rb, thats the only child that moves, attached to it is a (cinimachine) camera and the animator parent that holds the rig/animations depending on the character I want to spawn, I take it a step further and put the head mesh of the rig on a different layer and make sure the camera does not render that layer to avoid clipping at weird angles and animations
Would you mind showing me in a vc? I'm not really following
I cant vc, but I can try to elaborate, which parts are you confused by?
Does anybody know how can i access the classes and methods of a module in unity? I'm trying to see how it's used bcs there is no enough documentation
Which one in particular?
here you go, it's as simple as doing this
When your character looks down, does it bend over slightly or does the head remain still and only the camera moves down?
I know screenshoting using camera is a bad practice but I'm on discord phone soo ๐
And the photo is clear anyway ๐
I never understood that, unless your PC doesnt have internet access, couldnt you just log on Discord on your PC? Any solution you get, youd have to implement on your PC anyway, right?
In my game, no the head will remain still when the camera rotates down, im working on a multiplayer game so over the server, others do see the characters spine bend - if you do want the camera to bend with the characters spine, you could maybe create a second transform rig of just the spine and head, and have them tilt with your mouse input
I'm in hurry plus the problem description is in the text not the photo the photo is just to illustrate what I'm trying to say in case it wasn't clear
..
i see how i would get that to have the effect of the spine bending for the camera's pov but from an exterior point of view, the character would still be straight, wouldn't they?
Correct, because the rigs spine would be controlled by your animator, unless you use IK overrides to influence the rotation yourself, either setup on your rig (for example, from Blender if you made it there) or theres a Unity IK rig package that uses the Jobs system and some other IK controls to let you still play for example a "breathing idle" animation but also rotate the spine or hand or whatever while that animation plays, im sure there are other IK solutions or git projects as well
I just got IK working to keep my character's hands on their weapon as a test with hopes of going in that direction
Fair enough I guess, though your photo shows several namespaces, when you say "module" are you referring to a specific namespace, or Unity package or dll file or something else?
probably a total noob question but are there curve datatypes we can use outside of animation? For example, scaling floats for character attributes etc. Do people just use animation curves for this or is there some other asset type more suitable?
Im sure you can apply a similar setup for your spine too, im personally still learning IK setups myself, and used the IK rigger package, it was quite confusing to get (mostly) working how I wanted, but if your approach for hands work, I dont see why it couldnt be applied to the spine too
Thanks for the chat, I'm probably going to go with IK and have a target rotate around the head location or somewhere similar with the mouse Y motion. It's pretty intimidating diving into something without a direct tutorial for the first time in unity
AFAIK, without 3rd party assets, you can use AnimationCurve and Evaluate the time, or use a relevant Mathf.Lerp or Vector3.Lerp etc, or MoveToward if you dont want easing at the start/end of the value change - with 3rd party assets, there are packages like DoTween and im sure many others, thats just the first that comes to mind
Ok thats what I was figuring. Thank you
@fringe drift
How should I post the code?
Oh I think I have DoTween from some humble bundle ages ago lol Never checked it out. So thats what its for?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Let me know if you get it working, a lot of more specific problems probably dont have exact tutorials so theres a lot of trial and error with problem solving, but im sure you can find tutorials on IK in general, some of that knowledge you can maybe translate to your problem
@fringe drift https://gdl.space/itowehebiq.cs
I'm referring for the first nameapace for example I'm trying to use a speech recognize feature in it but don't know how or what are the methods to use
i'd bet you have NullReferenceExceptions in your console that you are ignoring
Its a wrapper for animation and lerping and curves and stuff, yeah its quite a good and popular one, though I personally have not used it, just heard good things about it from people who have
can confirm that DOTween is pretty good. it's also fairly easy to use
No errors right?
and just for the record, you use commas beautifully ๐
Following this tutorial to implement third person shooting:
๐ฌ How to make a Third Person Shooter Controller in Unity!
โ
Get the Project Files https://unitycodemonkey.com/video.php?v=FbM4CkqtOuA
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Learn to make awesome games step-by-step from start to finish.
๐ฎ Get my Steam Games https://unitycodemonkey.com/gamebundle
00:00 Third Person Sho...
But getting less than ideal results
I think the bullet is colliding with the player when it comes out the weapon but like, I have no idea how to fix that + the player is able to shoot backwards around corners
Maybe try to do a debug in awake
tried. When should the awake fire? First time you access a internal method or property, right?
If its a Microsoft namespace or System namespace, you can likely find it on MSDN, if its a Unity-specific package, its probably on the Unity packages documentation (which is separate from the regular class documentation), or you could search through IntelliSense as you type the namespace in a function to see what you can access, and if its documented (which most likely will be) the summary of those functions should give you a good idea of how its meant to be used
If i understood you right yes, is the gameobject active where the script is attached to
its currently not attached to a gameobject. I instantiate it inside of another script
Awake fires immediately after the script is enabled (assuming the game object its attached to is also active), if your not initializing properties, it should technically be fired before you call a property
You should maybe try to attach it maybe its the problem if it is check the instantiate line/-s
Anyone know why this code seems to execute the while loop instantly and ignore the WaitForEndofFrame yield?
The parameters are all coming in correctly
Debugging done? You shouldn't post in multiple channels
well yeah, it didn't help me much.
hm, currently its not attached to a game object, but is instantiated in a script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BattleSystem : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public bool StartBattle()
{
BattleManager manager;
string text = manager.AnnouncerText;
SceneManager.LoadScene("Combat Scene01");
return true;
}
}
I'm hoping for somebody to tell me that I misunderstand how while loops work there's definitely something I'm missing
there is nothing here instantiating anything
The loop is good
Where is Start battle called
Can you show where you call this method?
A while loop is what you call a head-controlled loop. It will always check the "while" condition before running the code.
in a game object, through a key down ("B")
This is what calls the method, which then calls the coroutine
The stats class then either starts the coroutine if the healthhealduration parameter is > 0, else performs the heal instantly
What is Yielders? Is that a class you made? Also are you sure your yield break isnt running before your EndOfFrame gets to? Also are you possibly running multiple coroutines or are you starting it from a Coroutine variable?
crosposting!?
This is where the coroutine gets started
OK. How do you instantiate a singleton class? I am at a loss rn. It seems the structure of it is correct... but its never instantiated through the awake
context
i will point out again that you need to put it on a gameobject in the scene
With what script do you add the component @gloomy mortar
No. I wanted to initiate it without adding it to a game object. I will fix that.
Okay, what's that Yielders.EndOfFrame? Try replacing with new WaitForEndOfFrame();
Or even yield return null that delays a frame
yeah I have already, same result
So you have to make a game object with BattleManager attached in every scene to access it?
if you want an example of a Singleton that will lazy load, you can take a loot at (or even just steal) mine https://github.com/boxfriend/Utils/blob/master/com.boxfriend.utils/Runtime/Utils/SingletonBehaviour.cs
If its a monobehaviour yes
alright
Yes
The BattleManager Manager; line is not enough to instantiate a script
Log the value of elapsedTime after you add Time.deltaTime to it. Make sure it's lower than duration after the 1st iteration of the loop. If that's right, then your coroutine might be running multiple times, affecting the variables faster
this simply declares a field that can contain an instance of that type
unfortunately, merely declaring that I have a parking spot for my Ferrari does not cause me to own a Ferrari
I know, thats usually how that works. I was not 100% how awake works, so I thought it listens to access to members of the class.
Awake runs when a MonoBehaviour is instantiated.
OK
(although if it starts out disabled or its gameobject is inactive, then Awake only runs after it becomes enabled)
Thank you for the help ๐ I gotta get used to how unity does things. Prior I did buisness programming for C#.
This chart may help understand how Unity functions fire: https://docs.unity3d.com/Manual/ExecutionOrder.html
You can think of Awake as a sort-of constructor call. It's executed when the object this script is on is created
ah ok. ๐ Thank you.
thank you too
Mind if I DM?
Logged all values repeatedly, something weird is going on
anyway I'll move on to an alternative solution
I think I figured a lot out. Managed to use the BattleManager class to fill the text dialog boxes in my combat screen ๐ thanks again for the help.
Hey, guys! Can someone told me and give me a very detailed explanation of what actually is the serialized field??
there's not a lot of detail to provide
"serialization" is the process of turning an object into data
Alright then
and then "deserialization" is the opposite: data to object
a serialized field is one that Unity knows how to turn into data and back again
So, for which purposes we are using them?
if something is serialized, it can be shown in the inspector and is saved in scenes/prefabs
by default, only public fields are serialized
so [SerializedField] is used to say "i want this to be serialized"
even if the field is not public
So, it works like public?
Not really
i would not think of it that way
public is an access modifier. It controls which classes are allowed to see that field.
[SerializeField] has no effect on that.
[SerializeField] is private. but expose it to the unity inspector
Is this in advanced programming, I am a beginner and I have not learn it yet
its hard to explain if you don't know the concept of serialization xD
you do not need to understand the guts of the system
all you really care about is that:
- public fields get serialized
- non-public fields with
[SerializeField]get serialized - only some types are serializable
I want to understand just the logic and when I get to that I will learn how to use it
Alright
Can I find it in documentation?
Why it seems to me very hard to understand and also it seems to be very complex?
Do I have to learn all of that
not really, but you should at least understand why you need to slap [SerializeField] on private fields
: so that unity knows to save them
Serializefield private just means it shows up in the unity inspector but it cant be accessed via other scripts bcs its still private
Alright, I catch it
So, you actually don't have the permission to call that scripts variable in the other script if I am not wrong right?
only the class that owns a private field can see it, yes
OK. Maybe I can help.
Lets take a big picture, right? You see colors, you see a form and you see certain strokes with pen or brush.
Thats the "object", aka an element that is hard-typed and has many attributes attached.
A serialization is the path to make this picture into a generally recognizable string of data, which can be reconstructed to be used again.
It is like a translator from a specific language into a universal one.
you'll get a compile error if you try to use a member that you don't have access to, and your code editor will not suggest using them
(a "member" just being anything attached to a class, like a field or a method)
Sure, if you make some progress you could either ping me here or DM me, thats fine
Yep
im making a multiplayer game using photon and my script is not working, I am getting no errors.
Launcher.cs: https://hatebin.com/vynjjmjcle
MenuManager.cs: https://hatebin.com/pzccajpvds
Menu.cs: https://hatebin.com/awllqgznkp
this will probably sound dumb but im incredible confused. I manually assign this in the inspector and it works fine. But in builds it doesent seem to work.
Would it make a difference if it was public instead?
no
agh im so confused, for some reason theres a part of my project which just doesent work at all in builds, but works perfectly in editor
Maybe you ought to explain what doesn't work etc
yea true, alright lemme write this out
have you looked in the player .log to see what is happening?
wheres that? in the build?
ffs. google unity log files
im making a multiplayer game using photon and my script is not working, I am getting no errors.
Launcher.cs: https://hatebin.com/vynjjmjcle
MenuManager.cs: https://hatebin.com/pzccajpvds
Menu.cs: https://hatebin.com/awllqgznkp
but theres no issues in the editor which is what this is for right? the problem im having is in the build
yes, and a run build will write a player.log file
do you think I am telling you this for the good of my health?
https://docs.unity3d.com/Manual/LogFiles.html
Player-related log locations
To view the Player log, open ...
Which of these scripts? You posted three here. Also what doesn't work about them? Seems like you've put logs here and there, is everything getting executed at the times you expect?