#archived-code-general
1 messages · Page 176 of 1
yeah i need to create them, then add to the Deck's List<Card> which will actually be a Stack, gotta change that
so i think this shouldu work
so would it be like Card.CreateInstance("Attack")
?
Don’t use SO to represent mutable data
why
I would store the actual card (the CardClass created with these stats)
yeah i thought about that, but if i'm not showing them in the game yet, why would i instantiate the GameObjects?
typically thats why my Card is the Monobehvaior and CardSO is my scriptable object
you need a class to read this data (SO)
Oh yes, I do! But I wasn't going to create the gameObjects until they are in the Hand, on the screen
thats why makes SO great you can just make a slot for this Data and swap them out
sure depends on you ig, I create the cards, keep them hidden inside the deck, then show it when player interacts with deck
I could see that use case you just explained, because if the cards have temporary in-game modifiers, or upgrades... things that would be pertinent to a player's custome xperience, then instantiating all the cards in a hidden way might be better
if you need to apply more data like buffs and whatnot, the card copied the data from initial SO data then it can mutate its own data because its a card not cardSO
i was wondering if it might be more resource intensive to pre-instantiate all the cards though? purely from a resource standpoint I'd think that only creating GOs in-handmight be more efficient... BUT at the cost of not being able to do what you're mentioning above.
How should I go about block face culling
Why not have a CardInstance class that holds a reference to a data SO plus extra stuff for upgrades e.t.c
Or just call it Card
thats what they have already iirc
Ah
they're just confusing which one to modify i think
yea that's the GO right?
or is that different than a GO
Yeah can be
you followed that video from brackys right ? I think
Just POCO should be enough
CardDisplay iirc is called on yours
yeah
thats your actual Instance that holds the SO data / reads it
It doesn’t have to be MB or SO
yea its easier to work with MBs tho
what's MB?
MonoBehaviour
ah gotcha
it can sit on a gameobject when MB
I think you ideally want 3 classes:
- A data
ScriptableObject - A normal class that holds a reference to data and extra modifiers
- A display
MonoBehaviourthat holds a reference to an object of the class and displays it
bump
thanks so you're saying I don't need to instantiate the GOs in the deck at all, just use the normal class to do that! makes sense
is GO & MB synonymous in most contexts?
Yeah, for example the player deck can now be a list of the normal class. Then when you draw a card, you can instantiate a display and initialize it with the card object from the top of the deck
I’d generally call second one “Model” and third one “View”
MB is needed for putting any script on a gameobject
Unfortunate this is more difficult for me, I have a project where I work with multiple canvases and UI gameobjects.. need to store them as Card: MB to move them between decks (different canvases)
I may have to do that as well, I have multiple scenes for my project already
Is that the only way to save a deck between different scenes & canvases?
Having the cards as normal classes is the best way
Then the display objects dont carry any data and can be destroyed/initiated however you want
You definitely want to implement object pooling though
i'll read up on it, thx
yes exactly. my MB has a regular Serialzable class in it that holds that SO data
When dealing with UI there is a special consideration to take as well
I'm switching to unity any tips to make a tower defense like a yt tut
Ah UI is such a pain in the ass to make a game with
youtube has a lot
also don't crosspost
bump again
doesn't change that probably no one knows what you mean..
been coding a while
never heard of this
I'm making Minecraft-like terrain with blocks and I need to cull the blocks that aren't visible to the camera to save performance
Ohh so you're making your own blocks? hmm thought you meant Backface culling lol
Nope lol
I originally made up the blocks of 6 planes, which I disabled their renderers when they weren't needed, but now my blocks are one solid model
That happens automatically already
wouldn't be easier to cull separate planes then one whole giant block?
Yes but its more resource intensive I was told
Are you sure? My performance is awful
yeah I havenn't dipped toes too much in generating meshes sorry this outta my knowledge 😅
maybe a shader could help culling certain areas?
idk if it would help perfm
What makes you think culling is the problem, did you profile/frame debugged it
Well if I only have one layer of blocks my performance is a lot better, so I just assumed
also where is the profiler? I haven't been able to find it
Window > Analysis
Thank you
wait idk
its something like that
They probably want the frame debugger instead
yea good point
all the links are there tho
i aint google
lol
Whats the difference? might be a dumb question lol
By default blocks should be culled if they're obsucred by a gameobject marked as static i think. https://docs.unity3d.com/2019.3/Documentation/Manual/occlusion-culling-dynamic-gameobjects.html
you can like step through how your scene is rendered
yea thats a lot of dips
Yep
You have script/physics overhead as much as rendering
Editor adds some overhead too iirc unless you do DeepProfile no? or standalone?
None of my objects are falling or getting pushed around
besides the player
it's categorized as "others"
ah ok that make sense
Doesn’t matter unless your blocks are static, still simulated
They are
Should look into combining all of the cubes into larger meshes.
not like Kinematic static, like gameobject.isStatic i think
Tons of individual objects is part of your problem.
How would I do that?
How can I set them to that?
Thanks I'll take a look
I think thats static batching
I shouldn't affect physics though
No Rigidbody = static collider
Take vertices from all cubes and put them in one vertex array. Take all triangles and build a new triangle array. Combine the materials from all the cubes so everything is colored correctly. Turn off the mesh renderer on all of the cubes leaving only the collider and then just render the big mesh.
You mentioned minecraft. It isn’t rendering hundreds of individual blocks. It renders “regions” of 16x16x16 blocks. Where a single mesh represents the region.
I'm using chunks, theyre rendering every block in the chunk though
Well i am currently
When something changes in the chunk, you recompute its mesh
Should I put all of the loaded chunks into one mesh, or just each chunk?
Unity dynamic batching should handle it similarly if you set up your material properly
Yep you’ll have to figure out how to combine those cubes into a single mesh in order to get decent performance.
That’s why you look into frame debugger
Each chunk should have its own mesh
so only have to rebuild one chunk's mesh when you change it (place, destroy etc)
Got it, i'll work on it and let you guys now how it goes 👍🏻
Thanks for the help everyone
Hey @rigid island one more question sorry to rehash this but I wanted to load the SO asset template into my deck, right? I know you said I could make one more class but I wanted to try it this way to do a POC
So I was thinking of trying https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
But! I read something in another article that said doing this is bad practice, is that true?
This is editor script you cannot use in build
ok so how would I load the templated asset into the deck then?
without the UI of course
you can make make a list of your SO
if you only want data
If you need dynamic resource loading should look into Resources.Load
make list of POCO if you want to store instances
what kinda dynamic data do you want? you should only use this folder saving, or if you're reading a file, maybe like a json of cardData from external source
I think this is what I want. I want to be able to store the templates as assets and load them into the list of my SO
wdym by templates exactly ?
Attack is just a created asset from SO
ok so should I use Resources.Load to put that into my SO list? Cuz I don't want to deal with assigning their attributes every time.
Resources.Load would probably be handy just like not having to drag the SO manually into a list , I suppose you'd have to put them all in that folder and load them that way.
defeats the whole point tbh, you mind as well just toss all those into a list inside inspector
uhhh wait but the whole point is to be able to pop them off the deck into the hand right?
so i need script for that
or like if a user is adding cards to their deck in the game, or removing them etc
Resources.Load is an editor only function it won't be used by user
your player can just deal with a list of your POCO that have the SO
keep those inside a List<Card> as your available cards
you can probably split that further into separate lists ig
public List<Card> AttackCards
public List<Card> DefenseCards etc..
np! hope it clears up a bit 😅
yes and I see what you're saying, I guess I just wanted to load them in with code so I don't have to deal with all the annoying UI stuff
but i get that is only for a setup step
prior to the player doing anything or deck management/etc
yeah basically you would create all those SO and put them inside a special Resource folder in order to load them through script instead of using inspector
yea makes sense
Resources is bundled with the build
You might be thinking of AssetDatabase which can in fact only be used in the editor
Ohh I think I confused it with once your build with it you cannot change its contents or move stuff around but you can read from it just fine yes?
I don't know about that
Idk lol I never use it tbh never seen the needs for it.
If I need dynamic content I stick to the persistentDatapath , or like AssetBundle or addressables ? (forgot which one lol)
So I'm trying
public void addCard() { Card currentCard = deck.cardStack.Pop(); prefab.card = currentCard; GameObject cardGO = Instantiate(prefab); cardList.Add(cardGO); sortCards(); }
but issue is that the prefab's script contains the Card object, I don't know how to add the currentCard into it?
the 2nd line causes an error
what error
'GameObject' does not contain a definition for 'card' and no accessible extension method 'card' accepting a first argument of type 'GameObject' could be found
which totally makese sense, I need to add the card to the prefab's script, not the GO itself
right - also why are you doing it to the prefab
you generally should not modify prefabs
you should be setting the card on the newly instantiated card, right?
prefab<GetComponent>().SomeScript.card = currentcard;
You should change:
public GameObject card;
tocs public CardHandler card; or whatever the Card prefab's script is called
that will make your life much easier
then you can do:
CardHandler newCard = Instantiate(prefab);
newCard.card = currentCard;```
man you should really change that Card class to CardSo and make a POCO class for Card @scarlet kindle
yes I agree with you
@rigid island
it's really just a POC but maybe that's just shooting myself in foot
huh whats POC
proof of concept
just to see if i can actually deal a card into the damn hand
lol
yes but you have to deal with instances from SO never directly modify SO class
let me try that
yeah i know, but i'm not modifying the SO here. i agree with what you're saying
for the actual game will definitely need another class in between them
it's giving me conversion errors when I try to do that
I have
public GameObject prefab; public DeckScript deck; public List<GameObject> cardList;
and my code is
` prefab<GetComponent>().CardDisplay.card = currentCard;
CardDisplay cardPrefab = Instantiate(prefab);
cardPrefab.card = currentCard;
cardList.Add(cardPrefab);`
and now complains on last line for type conversion from CardDisplay (script) to GameObject
you didn't follow what I said
^
oh sorry I made a typo I guess
public GameObject prefab; needs to be public CardDisplay prefab;
Also this line is incredibly confusing:
CardDisplay cardPrefab = Instantiate(prefab);
don't name this variable cardPrefab. It's not a prefab. A better name for this would be like cardInstance
the Resources.Load isn't working sadly. I added the Resources folder and follow the directions in the link, not sure
Card attackBasic = Resources.Load<Card>("Starting Deck/Attack");
could it be the space in the folder name?
What is Card?
The SO
get an NPE when trying to reference the assigned object
Card attackBasic = Resources.Load<Card>("StartingDeck/Attack"); cardStack.Push(attackBasic);
if that second line is throwing an NRE then it's actually cardStack that is null
Does anyone know why my code is creating gaps inbetween the chunks?
private void UpdateChunks()
{
Vector2Int currentPlayerChunk = GetCurrentChunkPosition(player.position);
foreach (var chunkPair in chunks)
{
Vector2Int chunkPosition = chunkPair.Key;
if (Mathf.Abs(chunkPosition.x - currentPlayerChunk.x) > renderDistanceInChunks ||
Mathf.Abs(chunkPosition.y - currentPlayerChunk.y) > renderDistanceInChunks)
{
chunkPair.Value.SetActive(false);
}
else
{
chunkPair.Value.SetActive(true);
}
}
for (int x = currentPlayerChunk.x - renderDistanceInChunks; x <= currentPlayerChunk.x + renderDistanceInChunks; x++)
{
for (int z = currentPlayerChunk.y - renderDistanceInChunks; z <= currentPlayerChunk.y + renderDistanceInChunks; z++)
{
Vector2Int chunkPosition = new Vector2Int(x,z);
if (!chunks.ContainsKey(chunkPosition))
{
GenerateChunk(chunkPosition);
}
}
}
}
well at least i have 10 cards in the deck now. i'll call that a win.
what is the relationship between scale and position when using the rect tool in unity?
In UI?
Yeah in the editor
I mean UI canvas
Yeah
Don’t use scale for UI elements because anchoring does not account scale. Position you see is anchoredPosition relative to anchor
What happens if I Serialize, save to a file, then load a Serializable ScriptableObject that has all of it's fields private. Will it still work as a reference of the ScriptableObject within the project assets? Or since the fields are private, will it be incomplete?
I'm not sure I specifically understand this part:
Will it still work as a reference of the ScriptableObject within the project assets
There's an instance of it created in my project files
alright and what does that have to do with all the serialization stuff you mentioned
I wonder if it will properly load as that specific instance, from the file, or if it will be an incomplete version of it since it's fields are private (meaning not serialized afaik).
if it will properly load as that specific instance, from the file
it's definitely going to not be that specific instance. It's a copy.
or if it will be an incomplete version of it since it's fields are private (meaning not serialized afaik).
This depends highly on which serlaization mechanism you are using and whether there are any attributes on the field. For example Unity's serializer will serialize private fields if you have[SerializeField]on them
Oh okay, should be fine then, they all have [SerializeField]
Yup!
Hey, I'm trying to make a player movement script that reduces the amount of control a player has while in the air. Does anyone know how to do this?
if (grounded) {
// control player a certain way
}
else {
// control it differently
}```
right, I have that, but what formula would I use?
entirely up to you?
that's the problem, I can't figure it out
you haven't exactly provided any specifics about what differences you want
so it's just a game design problem at the moment
figure that out first
then think about the code
I'd hardly even say u need a formula. Literally just multiply or divide by something
knowing if it's a rigidbody controller or not is a start
The problem with that, if the player is going right, I want him to continue going right with the same velocity if the player continues holding right.
So the control you want is to not allow the player to change direction?
not quite. say the player is moving right at a velocity of 4, but the they jump. if the player continues holding right I want their velocity to stay the same, but, if they press left while in the air I want their velocity to gradually decrease.
Well we don't know how your movement works on the ground but that sounds just like normal adding of forces in the air
how do I display code like that in the server?
!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.
!code
float dirX = Input.GetAxisRaw("Horizontal");
if (IsGrounded())
{
rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
}
else
{
//to be determined
}
📃 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.
you're supposed to read the thing
not type that
if (IsGrounded())
{
rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
}
else
{
//to be determined
}```
void FixedUpdate() {
float dirX = Input.GetAxisRaw("Horizontal");
if (IsGrounded())
{
rb.velocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
}
else
{
Vector2 targetVelocity = new Vector2(dirX * movementSpeed, rb.velocity.y);
rb.velocity = Vector2.MoveTowards(rb.velocity, targetVelocity, Time.deltaTime * 2);
}
}``` something like this
what does 'addforce' do?
nvm I changed it
forces will add a bunch of complication here if you want speed limits etc
so with this script, can you change how much control you have while in the air?
so do higher or lower numbers give you more control?
higher, I got it
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, 0.1f, jumpableGround);
}```
k
thanks
!code
My player will not move left or right
📃 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.
Larrge Code 👆
Yeah I figured it out
ok for next time then
Thanks
But yeah, my player will not move at all
And I can't figure out what's wrong with it
you said you figured it out ?
No, I figured out how to display the code like code
no but Im telling you large code should go in a link not in a giant message code block
Ohhhhhhhhhh
a powerful website for storing and sharing text and code snippets. completely free and open source.
Here ya go
My player will not move at all. Any suggestions?
do you have any errors in console ?
expand info in playmode
I have colliders (the "Player" is an empty for 6 different parts of my player)
do you see rb moving
wait.. where is the collider
on player
did you check what the rigidbody values are while in playmode, expand Info on it
The animations work perfectly though
that says HorizontalInput is coming in
Hi. I am trying to hover an object. But when I start the game it jumps up a bit on the Y axis and THEN hovers perfectly. No matter what I have tried I can't make it not do the initial jump. Like, the original position is -100 on Y. It jumps to like -20 or something, then hovers between let's say -26 and -36 or whatever. What is making it jump up 70 ish units on the y axis?
public class UIHover : MonoBehaviour
{
public float hoverHeight = 1.0f; // Height of the hovering motion
public float hoverSpeed = 1.0f; // Speed of the hovering motion
private Vector3 initialPosition;
private void Start()
{
initialPosition = transform.position;
}
private void Update()
{
Hover();
}
private void Hover()
{
float yOffset = Mathf.Sin(Time.time * hoverSpeed) * hoverHeight;
Vector3 newPosition = initialPosition + new Vector3(0, yOffset, 0);
transform.position = newPosition;
}
}
this is a UI (Canvas) object?
yeah
so it's initial position will be controlled by the RectTransform and the anchors used
man i was doing so well
i had finally figured out how make my character face a direction without actually movign it unless the key was held for a certain amount of time
but now the animation is bugging
oh lord, how on earth will I account for that
!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.
private void Update()
{
move = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
print(anim.GetBool("moving"));
}
private void FixedUpdate()
{
if (move == Vector2.left || move == Vector2.right || move == Vector2.up || move == Vector2.down)
{
if (move.x > 0)
anim.SetTrigger("facing right");
else if (move.x < 0)
anim.SetTrigger("facing left");
if (move.y > 0)
anim.SetTrigger("facing up");
else if (move.y < 0)
anim.SetTrigger("facing down");
moveTimer += Time.deltaTime;
if (moveTimer > moveBuffer)
{
rb.MovePosition(rb.position + move * speed * Time.deltaTime);
anim.SetBool("moving", true);
}
}
else if(move == Vector2.zero)
{
moveTimer = 0f;
anim.SetBool("moving", false);
}
}
this is my code for the movement
basically if you input a direction (left, right, up, down), the player will face the direction you pressed, and if you hold it down for a certain time (moveBuffer), it will start walking in that direction
my issue is that for some reason the animation keeps jumping back and forth between the idle and moving animation
each direction has an idle and walking animation
and the transition from idle to walking is if the boolean "moving" is true, and the transition from walking to idle is if "moving" is false
but for some reason the animation jumps back and for between moving and idle
can anyone help me?
Just a quick look, not really looking too deeply but you're setting the facing direction even when the timer is greater than the move buffer. So it will set it back to idle before setting it to moving.
Add an additional check either around all four of your if statements for idle or inside each to make sure you only set it when moveTimer < moveBuffer
Though, generally speaking, this could be cleaned up a bit. But get it working first.
yeah i know this probably isn't optimal lol. i'm just starting out. lemme do ur suggestions rq
what do you mean by that first poitn?
point*
i want the player to face the direction before they move
Which happens while the timer is less than the buffer. The check you should be adding will only verify that and prevent it from being set once the buffer is reached.
ohhh
like this
if (moveTimer < moveBuffer)
{
if (move.x > 0)
anim.SetTrigger("facing right");
else if (move.x < 0)
anim.SetTrigger("facing left");
if (move.y > 0)
anim.SetTrigger("facing up");
else if (move.y < 0)
anim.SetTrigger("facing down");
}
ok so that parts good now
now there's a new issue 😭
ignore the music i forgot to pause it ☠️
basically now the player doesnt change direction until we stop moving
Because you're not resetting the move time between directions (which you don't want or there will be a pause). But your animator has no way to transition to another move animation if it's already running a different move animation.
Quick hack would be to hook your move states to the any state as well. But you can see how you're getting into messy territory.
yeah i feel like that could also start problems
so the only solution i see is making transitions between all of the moving animations
but that feels tedious
Try the Any State option
Yep. Leaving it shouldn't be an issue, it's just redundant.
why does something like this:
[HideInInspector]
[field: SerializeField]
public virtual bool ShowSingletonErrors { get; protected set; }
still show up in the inspector? I verified that there are no errors and the code compiled
it looks like [HideInInspector] is ignored for fields?
I applied my two braincells. [field: HideInInspector] works
oh jeez this did not work
You are putting SerializeField attribute on field, so should HideInInspector apply to the field as well
But why do you even need this
Lol. Did you correctly apply the parameters?
Mecanim makes me sad
yup. from Anystate to the walking animations if moving == true
[field: HideInInspector] works, as I really should have guessed
I'm just making a generic singleton<T> class, and I wanted a way to choose, when writing the code of a deriving singleton class, if the errors like "singleton already exists" or "destroying an object with a singleton" should get displayed with Debug.LogError
now all someone needs to write is
public override bool ShowSingletonErrors { get { return false; } }
in their class when deriving from my singleton class, and the errors will be gone
Well, you'll need to start debugging the states I suppose.
and I thought that setting it in inspector is cluttering it up
it faces the directions fine, but once i start moving it plays the walking_up animation over and over
So why that needs a SerializeField in the first place
maybe because it's the "last" transition, so since the walking animation can come from any state, the animation just transitions to walking_up
because I wanted it to be possible to override it in the debug inspector
but that doesn't work anyway, since it's a field
do transitions take priority?
Disable transition to self
You will need to set unique parameters for the moving direction, the same way you're doing for idle.
oh
Because if they're all sharing the same parameter, it won't know which you actually want.
that's true
Any state will keep evaluate to current state and start transition
where is that option
is it "Can transition to"?
Yes give your inspector some more space to show text
Well overridden value will not be settable from inspector
Because it'd be just method call
it made up a whole new animation because it keeps switching from walking_up to walking_right
the frame rate is too fast for obs ☠️
true, but what if it's not overriden? it'd be cool if it appeared in there, then, but it does not
its in between up and right
all that did was instead of it staying on walking_up, it started switching between walking_up and walking_right at superspeed
hmmm
transitions can take multiple conditions to trigger right?
Yeah
IVE GOT IT
well i have an idea
i will make the transitions from any state to idle have 2 conditions
its facing a direction and moving == false
and from any state to walking, it needs to face a direction and moving == true
then i will get rid of the if statement checking if the moveTimer < moveBuffer
because i need the direction to be able to update while moving
and the animation switching glitch shouldnt happen because idle will need moving to equal false
IT WORKED
MWAHAHAHA
IM A GENIUS
now. next step
make it so i can go diagonally
right now what happens is if i press down 2 keys at once, the player stops and it plays the idle animation for one of the directions im holding down
if only we were able to set a scene of a game object as easy as go1.scene = go2.scene; or go1.SetScene(go2.scene);
my life would be easier
thanks, i think this could work for my application
thinking back, there's no way I would approve the left version, but I'd approve the right with some additional comments 😅 I'm starting to get worried
I'm lost on how to actually do this. The texturing stops working when I try this. I turned on GPU Instancing, and am down to like <100 draw calls but still 30 fps, so I don't think rendering is my issue
If you're solving a performance issue, you should first use the profiler.
I see that you don't know how to use the profiler. That screenshot provides 0 useful info.
Look up resources on how to use the profiler or read the manual.
Hello i wanna ask. I wanna snap gizmo in unity editor. I use Handles.FreeMoveHandle to snap the gizmo but i must press ctrl on keyboard. Can i snap gizmo without pressing ctrl on keyboard ?
uhhh i honestly don't know what you're saying srry
i'm just dumb
You have too many game objects because you have every single cube being a game object.
That graph you posted looks like around 1/4 of the time per tick is spent on scripts. Presumably because you have a script on every block.
1/4 of the time is spent on rendering. Presumably because it is having to determine which blocks are visible.
1/4 of the time is spent on physics. Presumably because you have tons of colliders.
Merging them into a single mesh doesn't only solve rendering.
You can trigger transitions by code. It is going to be much much much more clearer than the basic animator based transition graphs.
Just a suggestion
yeah i figured it out
basically i have a bool "moving" and 4 triggers, one for each direction
and if "moving" is true, the character will walk in whatever direction was triggered
and if it is false they will stand still facing whatever direction was triggered
You can do this by ;
On move, get current direction's animation hash, if current animation doesnt match the hash, play the animation with the hash
I somehow don't like the unity animator stuff, they are weird
i would do that but i dont wanna fix what aint broke
Yeah you are right, just saying to let you consider in further projects
my code is functional, even though it probably isn't optimal, its the best i can do at my level
yeah i'll try it out on my next thing
and the movement is surprisingly smooth so yay me
Whats the point of interfaces i dont need something telling me that i need this its either i have it or not
how do you enable unsafe in unity
trying to do some memory copying seems i need to enable it some where
very helpful lol
At the basic level for inheritance. If you have 1 class then yea it doesn't really make sense. But if you have 10 classes that all need to implement different versions of the same things then interfaces can become useful. Since anything references those 10 things don't have to know exactly which of the 10 it is, but just needs to know if it implements the interface or not.
For abstraction of course.
It's the same reason why you'd use inheritance.
ah finally found it
Using GetComponent<IMyInterface>() to get one of 10 different implementations is pretty handy
i was checking the answer of someone on stackoverflow and I found the variable Outline
That's a Type which is USED for a variable. But Outline, itself, is not a variable
im getting confused rn
Pretty sure it's this component, in case you wanted to look at the docs. Edit: ah, you found it yourself. Nm
https://docs.unity3d.com/2018.4/Documentation/Manual/script-Outline.html
so it can store a data from my Physics.raycast and gives to my text some cool graphic components?

maybe im tired
thank you Aeth
gn
It could be a custom class. There's no knowing that without seeing the author's project.
Quick question - when you set the time in a timeline playable, does it traverse the tree and set the time for each of the playables in that timeline's subgraph?
Cant u just do this with inheritance
This isn't really coding, but I don't see a more relevant channel:
How expensive are mesh colliders really? My scene is covered in them, and I don't really see an alternative to have traversal on and around these meshes feel good
Is there a way to use collision brushes etc to manually setup scene collision to optimise this? (Like in Source Engine)
A single class can implement multiple interfaces. You can only inherit from one class. There are other nuances that are interface specific.
The only reason i can see myself ever using interfaces is grouping classes together inheritance abstraction and interface always confuse me
Interfaces differ from to other in the sense that they separate API from the implementation.
Interface is a contract that tells you that the class implements a certain API, but it doesn't reveal anything about the implementation itself.
Base class promises that there is at least a basic implementation. Unless the method is abstract. In this case it is almost the same as an interface, except that you can only inherit from one base class, while implementing multiple interfaces is possible.
Can interfaces contain any implementation in C#? I know with Java you can now do some stuff with default methods etc
That is a fairly new thing to C#, so it will exist depending on what Unity version you use.
There is interface default implementation, mind that you'd need to cast to the interface (or generic constraint) to use
if I have something like
newObj.transform.position = Vector3.zero```
will Awake functions on scripts in newObj be called before, or after setting the position to Vector3.zero?
Or to form my question differently, does Instantiate internally call Awake on all scripts attached to the spawned object? Or is it called during the main loop, on the next frame
Before
thanks! How about OnEnable?
Same iirc
ah
my goal is to have something that will be call after that, but before the Start() on other scripts on that object
Make a method of your own that you call, it's the most robust way of doing it
Awake/OnEnabled will be called when Instantiate if your object is active
Start will be called on next frame
What is the difference between CapsuleCast and CapsuleCastAll?
that's for android studio? how do I open from my game(mobile)?
One only hits the first object, the other hits everything it passes through
Thank you
Is it okay to set Rigidbody velocity in Update() rather than FixedUpdate?
Moving objects around in VR is a jittery mess with fixedupdate
But I know physics is ran on fixedupdate
It's for Android. Look up how to run native android code from your Unity app
This usually happens if you are trying to read input in the fixed update
Read the input in the update, then move in fixedupdate
It's not my code
The motion will be exactly as jittery if you set the velocity in Update
It's the XR toolkit
I figured it might be
You need to enable Rigidbody interpolation to make it not jittery
It has nothing to do with XR
Btw, talking about physics, is it performance heavy to use CapsuleCastAll?
From what I've read, this is too slow to feel good
In the character, constantly looking for collisions
As obviously before fixedupdate hits it has no info on current position
IDK what that means
So it's always behind by an update cycle at worst
It basically lags, without stuttering
The fix I've seen online is parenting the object to the player hand object
And I don't quite understand how physics can still work correctly like that
It can't
so, there is no way to do it with c#?
I have tried this and it does nothing.
AndroidJavaClass jc = new AndroidJavaClass("android.os.Environment");
string path = jc.CallStatic<AndroidJavaObject>("getExternalStoragePublicDirectory", jc.GetStatic<string>("DIRECTORY_DCIM")).Call<string>("getAbsolutePath");
// Get the path of the folder you want to open
string folderPath = Path.Combine(path, "Game Screenshots", "Map 1");
// Create an intent to open the file manager
AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent");
AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent", intentClass.GetStatic<string>("ACTION_VIEW"));
// Set the URI to the folder's path
AndroidJavaObject uri = new AndroidJavaClass("android.net.Uri").CallStatic<AndroidJavaObject>("parse", "file://" + folderPath);
intentObject.Call<AndroidJavaObject>("setDataAndType", uri, "resource/folder");
// Get the current Unity activity and start the intent
AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
unityActivity.Call("startActivity", intentObject);
The typical approach is a proxy physics object that follows the XR moved object
My guy use code blocks, poor praetor blue xD
Hm, that seems like a neat solution
This thread seems to suggest you can get away without it
Does physics still work properly if a parent of the object has its transform changed?
I'm assuming not
@leaden ice is it bad to use CapsuleCastAll to check for collisions? I'm afraid it can get laggy
Don't ping people outside the conversation
Oh ok
Sorry
Anyways, question still stands for other people I guess
Are constant cchecks with CapsuleCastAll bad?
the answer is pretty much always: it depends. Do you need a cast in the shape of a capsule that goes in a direction and returns everything hit, and do you need it checked often?
if so then use it, it exists for a reason
I do, yeah
You should state what the actual problem is, so people can tell if theres a better way.
So, I want to make a controller for my character, but he is kinematic. I want to check for collisions using CapsuleCastAll. The thing is, I've read somewhere that doing those casts are bad and I should find an alternative.
Tho I can't think of anything else to check for collisions
You know what? Nvm, I'll just deal with it later if any problems arise
If everything is bad to performance then there wouldn't be any games at all
profiling is your friend
True
how can i get the rotation speed of a transform?
i wanna know how fast a transform is rotating
why? and how is it rotating?
Transform doesn't have a rotation speed.
rotating based on first-person mouse movement
well yeah but isnt there a way i can calc it
Sure there is.
rotation speed = (rotationB - rotationA)/ time between B and A.
for euler angles sure, if you're trying to do it based on quaternions itll be a bit more math
You already have the rotation speed, it's the amount you're rotating it by (divided by deltaTime)
heyo, so I'm trying to make a custom cursor for my top-down game, that is like an arrow that points away from the player character towards the mouse (so the cursor needs to rotate, basically).
I've created a UI element that follows the mouse via a script, but there's a frame delay between the actual cursor and the custom cursor.
Is there a way that I can script my "UI cursor" to update its position immediately with changes to the hardware cursor? I can't think of a way that'd be possible, but I figured it wouldn't hurt to ask.
I've also investigated using a virtual cursor to override the hardware mouse... but from my understanding, this means the actual game cursor would still have the frame delay. Is there a way around this delay? Is the frame delay noticable, in your experience?
The complication here is that I'm designing a sort of twitchy game and don't want to worsen the player experience...
There's no way around the delay. The only thing that's going to feel as nice and smooth as the hardware cursor is... the hardware cursor
Maybe make 8+ cursor textures for directions and swap them out?
that's a mad workaround fore the delay issue what a genius
If somthing does not work as intended, don't fix it, make it intended!
goosebumps
Unfortunately I'm looking for 360 degrees of smooth rotation, (that's a lot of sprites!), I don't think I can tangibly do that... In theory I guess I could somehow procedurally generate them?
I think I'll just investigate implementing a virtual cursor and see how it feels
You just want an arrow that orbits around your character ?
But in principle I think the sprite sheet style approach would work
Sort of, yeah
What style game is this?
Why don't you use a simple sprite with a pivot centered on your character instead of making it this complicated ?
Juste hide the cursor if you don't want the pointer to be visible
Would that allow me to move the cursor closer or further away? I'm not familiar with that approach, still kind of a unity noob
Well, if you code it, yes
I don't want to hide the cursor because if the real cursor is still doing the clicking it will be weird when interacting with things
i think i've already done what you're suggesting, btw
(i think)
IIRC diablo has used 8D sprite sheet cursors for years
theres another design complication here
which is the little spike going down from the cursor
Maybe not since Diablo 2? I don't recall
that indicates left/right side attack direction
(think like Mordhau)
so uhh... double... triple the sprite count for the spritesheet mouse 😄
Yeah that's not gonna be feasible with hardware cursor
But if you want the cursor to face the character you could go with camera.ScreenToWorld() look it up I don't recall exactly the usage, calculate the angle from that point to the player and use that angle to rotate your cursor no?
you can rotate the hardware cursor sprite?
I would recommend Plane.Raycast for this POV
will look into this, thank you
i've been doing the camera stuff
i think the most sensible approach might be to just use a virtual cursor to command the UI, and hide the actual cursor
(and have the frame delay)
also i guess thats necessary for controller support?
(OR just scrap this questionable design entirely and come up with a better way of indicating things)
regardless, thanks for the help, everyone 😄
Or rethink the design with hardware cursor+software aspects in mind
I'd look at Baldurs Gate 3 and Divinity Original Sin 2 for inspiration
They have a hardware cursor and lots of corresponding software particles and indicators integrated nicely
Oh! I actually haven't even considered thinking about how games deal with this. WELP now I can't play games without screwing around with the cursor to try and tell if it's hardware or not
Thanks for the inspiration, will definitely mess around with the bg3 cursor 😄
This design challenge seems to be quite valuable
Hello, after I create a Scriptable Object with .CreateInstance(), do I need to make it a .asset file? (with asetDatabase.CreateAsset) I don't want it to see it in my asset files, but i'm scared it will get deleted
I have a question relating map if anyone know how to solve it somehow, I have a map with edit function which you can add markers into it, and then u load it out (through location data), are there any way i can anchor the markers so it stay the same on different resolution? Cause atm when i load it out using theirs local position, the location will be wrong because map is resized on different resolution but markers aren't
If you want to save it as an asset, yes
if I won't save it as an asset, will it get deleted?
It won't get deleted so much as it will never have been created in any persistent sense
Well, do files get deleted if you don't save them ?
hm
so if I have a list in an editor window somewhere with a scriptable object that's not saved as an asset, if I close and open the game, it will be deleted?
You'll lose the SO with the data it contains, yes.
Something random when you are about to finish your project and upload your game are you guys using smthing for anti cheat?
it's a bit late in the day to think about anti-cheat when the project is finished. If you are serious about stopping cheating it needs to be built in from day 1
Hey guys.
I am trying to re-order children of a prefab. I am getting the following error:
"Children of a prefab instance cannot be deleted or moved, and components cannot be reordered"
I am trying to re-order children of the prefab itself - not an instance of a prefab.
Any thoughts?
show the window you're trying to do that?
if it's in your scene, it's an instance
you need to double click the prefab in your asset window to go into prefab mode and change it there
Like I said, I'm modifying the prefab itself, not the instance of it
Trying to move 'Blocker' above 'InteractionArea'
show your Door prefab
the non variant
Sorry I'm not following, what's the non-variant?
you cannot modify BasicInteractable's hierarchy which Door has inherited
so that's why
Awesome, tyvm!!
in the future ask in #💻┃unity-talk , this isn't a code issue
You're working on a prefab variant, so it has to respect the base prefab hierarchy
(for some reason, my window didn't show more recents messages...)
Awesome, cheers:D
<@&502884371011731486> Offensive user name
Hi guys, is there a "best practice" in creating classes for a player controller?
I.e. my Character consists more or less of 3 scripts - a Cam-Manager that manages rotation, a Kinematic Character Controller that handles the movement input and rotates with the rotation of the cam and a weapon manager, that controles weapon selection, firing and the zoom.
So when I want to zoom, my WeaponMgr recognizes the button press and sends an event to the Cam Manager (over main player class) to start zoom with parameters given by the weapon object.
When my Character slides down a slope, the KCC sends a signal to Cam to restrict rotation angles, so my Character can only look down the the to a certain degree.
Is this "the right way" to handle communication between such entities, is there another State Machine in between that syncs and handles stuff more appropriate? Maybe I'm just stuck in a analysis paralysis but synchronizing all 3 becomes a bit hard to oversee...
This seems like a good approach to maintain SoC (Separation of Concerns), if you wanted to classes your have less of a direct dependency on the player class, you could utilise events (look into the Observer pattern) and that would be a good way for your scripts to communicate while being further decoupled (this makes it easier to change classes/requirements without needing to have hard dependencies between classes when communicating). There are multiple approaches/patterns that you could use for your use-case though
Hi. One question, what is wrong with this code because it doesn't matter which button I press it always debugs the same value please:
for (int i = 0; i < Tabs.Count; i++)
{
TabsButtons[i].onClick.AddListener(() => Debug.Log(i) );
TabsButtons[i].onClick.AddListener(() => SelectTab(Tabs[i]));
}
Look into "closures", that's just the issue here
capture the i first
Use of swear words is not prohibited here, unless it's a slur or directed at someone or particularly gratuitous. It's more of their problem having an edgy name and pushing away people who might have helped otherwise.
!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.
fair. I'll just block him
Hello! I've got an issue with my character. I make him jump by increasing his velocity, and if the button is pressed long enough he will jump higher. However, if after dashing I'm still pressing the jump button, the character will conserve the momentum it got before dashing.
I'd be really glad if you knew how to help me with this! Thank you before hand
If you need me to show any code, feel free to ask :)
Reset the jump strength variable when dashing
Please just show the code before being asked. This is most likely a code issue
I'm going to post the code in a thread
I've fixed the issue with another method, thank anyways, as your advice was useful as well ^^
Is there still an issue? @hollow dune
Nope! What I did, was to change the variable that measured the timer for the press while jumping, to 0, when the dash started.
So, when the dash finished, that timer would be 0, so it wouldn´t go up anymore
okay
Oh yeah, the observer pattern, I remember it 🙂
I'm beginning to become a bit confused about all the possible combinations of Camera/Character States and what could trigger when.
Will have a look into it. Any other patterns I can check out?
Got another question btw, how do you guys handle animations in your code?
I have specific movements that solely rely on calculations rather than Input (i.e. climbing up a ledge, which calculates an end-position and moves the Character via an animation curve).
Do I just play a real animation while my player object is moving via an animation controller or how is stuff like this handled properly?
There is a book on game programming patterns which covers the some useful ones for game development such as command, observer and state pattern. It also wouldn't hurt to look into the SOLID priniples in my opinion. You don't have to follow them religiously but each principle builds on one another and can be a good way to think about code architecture. While they are a lot of good resources about SOLID, this is a good playlist for applying those concepts within Unity: https://www.youtube.com/watch?v=Eyr7_l5NMds&list=PLB5_EOMkLx_WjcjrsGUXq9wpTib3NCuqg
Check out the Course: https://bit.ly/3i7lLtH
Learn how to apply the SIngle Responsibility Principle (the first of the SOLID Principles) to your Unity3D game. We'll start off with a sample that violates SRP completely, then dive into how it can be refactored to be clean and maintainable.
More Info: https://unity3d.college/2017/01/10/u...
Has someone with riderflow also came accross this error: Assertion failed on expression: 'manager != NULL' when loading a scene in play mode? It doesn't affect the game itself, but it's weird that it keeps happening every time. Here's the full stack trace: https://hastebin.com/share/qituxezefa.xml
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Already know his videos, Jason is pretty good for this stuff 😄
Just wonder if my approach is "the right one" or if there's an easier solution, so I don't have to re-invent the wheel.
Like how do I move a character along a given path with proper animation (like my climb example)? Wonder if I'm doing it "the right way" by lerping my character position and playing an animation in the meantime using my animation controller.
there's no correct solution
but in my experience, splitting things across many scripts and using UnityEvents usually seems like a pretty good choice
UnityEvents are pretty slow compared to normal C# actions though, would recommend the latter one 🙂
Invoke 1000 UnityEvents and C# Events, compare the time needed, be surprised 😄
...Depending on your use case. UnityEvents are great for offering a design time interface. Don't prematurely optimize -- check the performance via the profiler
Would go the ScriptableObject route instead if I have to use drag&drop
SO approach is harder to justify IMO
Yeah but SO doesn't slow your calls down as much, at least in my tests UnityEvents were several factors slower
Premature optimization is the bane of many code bases.
In my opinion, you should limit interaction between the different component and instead relying on the player.
Camera does not talk to controller instead player listen to change in the controller then apply the appropriate modification on the camera. You want to reduce as much as possible interaction that might be unique to this situation.
My Player Class is kinda like the bridge between Unity and my other objects - it grabs all Input, pre-processes it for my other classes and keeps is synchronized with Update/FixedUpdate cycles.
Camera and PlayerController StateMachine only gets updated when Input occured anyway. So I guess I'm kinda there already?
This is what you said:
When my Character slides down a slope, the KCC sends a signal to Cam to restrict rotation angles, so my Character can only look down the the to a certain degree.
Oh yeah, but that's necessary since the sliding state depends on this feature, since it's a gameplay decision that my player can't rotate freely on slopes
You can do the same with:
Camera does not talk to controller instead player listen to change in the controller then apply the appropriate modification on the camera.
So Camera listens to the state and switches accordingly?
No, the player listen then act on it.
Hmm, good point
If you want to have a camera that has a close connection to the controller, I would make a specific Controller Camera.
Then, you could take the most of the logic out of the player and use this component instead.
Also, the Controller Camera would probably use a standard camera. The difference is that it would be able to listen on the change of the controller and change the behavior of the camera.
Note, that would be overengineering at this step. Having everything in player is better for the moment.
OK, so PlayerClass needs to observe the States of my CharacterController and change the camera accordingly?
Exactly. I think this would be better than having the Camera listen on the change of the Controller.
Also, do not name your class PlayerClass
Sure, those are not my exact class names, was just for the diagram 😉
Hey guys, how can I adjust the text transparency in unity?
Thanks
what text
Editor?
what component is this
I make a text using the textmeshpro for the UI
okay, have you taken a look at the component itself in the inspector
and do you mean you want to set the transparency through code?
yeah, or through the editor if we have a way to do that
ok so have you taken a look at the component itself
you see there's a color field?
yeah i can see that
my project is still loading
Already almost done with them
Next time you ask questions when you actually have the project open and can act on the help
You just wasted the time of others
okay i'll try
thanks
hello,
i need a little insight help if possible:
i've coded my object to shoot a target, so at first i'm able to exactly shoot toward the target and it was working fine
but once i've modified the target to be able to move randomly, the bullets go toward old target position instead of new target position, is there someone who can explain/simplify how i should target a moving object or how my bullets reach its exact position ? thanks
you're probably moving the wrong object or calcuating the target pos wrong
Gonna have to share the code
!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.
that's how my bullets are shot (this block is inside a bigger one in a coroutine):
bullet.transform.LookAt(_selectedAlien.transform);
Vector3 directionToAlien = (_selectedAlien.transform.position - bullet.transform.position).normalized;
float bulletSpeed = 100f;
Rigidbody bulletRigidbody = bulletProjectile.GetComponent<Rigidbody>();
bulletRigidbody.velocity = directionToAlien * bulletSpeed;
and as i said, the targetted object moves towards a random point at a constant speed
how are you moving the target
can you show hierarchy as well for the target
how to solve white border
private void MoveToPosition()
{
if (_targetPosition != _transform.position)
{
Vector3 currentPosition = _transform.position;
Vector3 moveDirection = (_targetPosition - currentPosition).normalized;
Vector3 movementVector = moveDirection * (movementSpeed * Time.deltaTime);
Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
if (_rotationMode == RotationMode.Free)
{
_transform.rotation = Quaternion.Slerp(_transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
_rigidbody.MovePosition(currentPosition + movementVector);
CheckReachedDestination();
}
}
didn't undertand this
the hirerchy , for this object. the one you're using this sccript
The object your script is attached to. Hierarchy = the object and its children in the hierarchy view in Unity
ah okay
i don't think it'll help but sure (i'm pretty sure the above codes are enough):
the bullets spawn outside of the object (so that they will be independent of it) and then go toward target, nothing more nothing less
i'm just asking for the logic that helps identifying the correct position of a moving target, but google is giving me complicated math formulas and youtube isn't helping as well
cause you showed the wrong thing thats why
ofc it wont help.
I asked the hirerchy for the TARGET
you
How will it help? Since I don't have eyes in your screen, I could at least tell you're moving the target and not potentially a child object or something else you're not seeing.. Idk your setup so its only a minimum we should see the setup, scripts alone cant help without knowing the context they're in
how do i reference a script component with a public int? I tried go.GetComponent<Script>().num=1; where num is the public int value in the script of gameobject go.
are you having error or something?
yes that works
assuming you use the real identifiers for things
Highly recommend saving the reference in a variable rather than calling GetComponent all the time though
hopeully its inside a method too 😛
Really, it's supposed to work? Maybe I am doing something wrong. Also, it is inside a method
also appreciate the tip
How does it not work ? Does it generate an error ?
Maybe if you explained what the nature of it "not working" is, we could help further
yeah i'm not dumb enough to move something else i'm not seeing sorry 😆 , there you go
Customer: "My car doesn't work, fix it"
Mechanic: "Ok what's wrong with it?"
Customer: "It doesn't work"
Mechanic: "???"
Customer: produces a horse
lmao
it doesn't have any hierarchy, it's literraly spawned directly on the scene
I gotchu. I'm not saying you're dumb lol just checking for common mistakes idk at what level you're at
[ObserversRpc(RunLocally=false)]
public void addBall4()
{
go=Instantiate(ball4);
go.GetComponent<Script>().num=1;
instance.scene = gameObject.scene;
InstanceFinder.ServerManager.Spawn(go,null);
}
oh we're dealing RPC
says is unknown symbol
can you show the full error ?
Is your script actually called "Script"??
"Script"
i thought it was reference what type of component but my script is called "Ball"
and if this is your level of C#/Unity knowledge you're making a mistake trying to make a networked game already.
You're trying to run an olympic marathon before you know how to crawl
yeah dw understandable, i'm usually precise when i ask questions so i found it a bit weird 😄
Then you write Ball
Ball is the component
any Monobehavior can be a "Component"
guys, I'm trying to validate the touch block in the mobile touch UI so that it doesn't recognize a certain function if clicked on in the UI, I'm using this code snippet but it's not working, can you help me?
ok, thanks
does anyone konw why this happen? it just says something went wrong
hmm is possible you can make video of what its doing right now or where is it aiming at ? something doesn't match up somehow..
IsPointerOverGameObject doesn't take any parameters.
You need to configure your IDE so it shows errors
do the package manager test
you might be net blocked or firewall
ok, thank you
if you look carefully, the lasers goes just toward the old position
here's a proper one
I'm assuming your targetting system is Off in the first place
it's in a coroutine
Are you making the projectiles children of the ship?
nope
i remember the first time i did this i was like wtf is happening 😄
the LookAt on the bullet itself is a little weird but prob non issue. How do you find/lock onto target, not sure you sent that
on mouse click
_selectedAlien.transform
just add the ref to the object in a private member
so i'm supposed to have the object ref when it's selected, which it is, but the lasers get shot at instant t and then the object move to t+1
and because it takes "a while" for lasers to reach the object so they reach the old position
often are you updating the _selectedAlien.transform ? maybe its shooting at their old pos when you clicked on them
you said a coroutine right
ah wait, i mean, i click only to select, but when i shoot i click on a keybutton
like to enable/disable shooting
where is this happening #archived-code-general message
kinda messy but
here
this one
Vector3 directionToAlien = (_selectedAlien.transform.position - bullet.transform.position).normalized;
yes
wait this is the bullet script?
not the enemy
#archived-code-general message
okay i've found the solution
i only needed to update the target position on the bullet prefab
and adjust velocity and direction
thanks for this
that was the enemy
ayee! as long its fixed lol
i needed a trigger and that was it, so really thanks
== is comparison, = is assignation
Also, the gameObject property is readonly pretty sure. Or a private setter public getter (the former makes more sense, but idk). You cannot assign to it
i am trying so that when the goes over a platform, there is a message in console saying "hit", but i just cant seem to get it right? can anyone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DetectPP : MonoBehaviour
{
public GameObject pp;
private void OnTriggerEnter(Collider other)
{
Debug.Log("hti");
}
}
the script is attached to the player and pp is the object i want it to hit
How do I debug XCode Simulator instance or app running in iPhone? I have a case where I click and do some raycast check. And this works for me in Unity, but not in XCode Simulator or iPhone. The XCode build is totally unreadable to me.
Show the inspectors of the two objects.
Alslo there's no reason to have a direct reference to pp if it's the object you are hitting
@rigid island Continuing from the error yesterday - the velocity is being registered, but the player is not moving
I can't even remember wat I did 2 hours ago, I'm gonna need the context from before lol
hmm right, I never got an answer on this
looks fine to me. Are you sure the colliders are overlapping?
The velocity is working in the Rigidbody (X velocity is going to -1 and 1 (GetAxis("Horizontal")), but the position is not moving
do you have logs disabled in the consolle or something?
as you can see....
put a box collider on the rigidbody see if it moves it
too me that tells me the rigidbody is indeed moving but isn't moving the transform of the object
or its moving something else
is Player child of anything ?
So you want me to put a Box Collider 2D in the empty gameobject ("Player"), where the RigidBody2D is
"Player" is the parent of 6 gameobjects (all the body parts). Why?
I said child not parent
Oh sorry. No, "Player" has no parent
You have an animator on the object - it's probably overriding the position
try disabling it for a minute
Disable the animator?
oh it seems like it, i added a debuglog statement in start() and it didnt print as well, how can i rectify it?
Ok
turn logs back on
@leaden ice You are a genius
That did the trick, but now opens another problem - what's wrong withg my Animator?
it's animating the position of the root object in the hierarchy
classic mistake
move the renderer that it's animating to a child object and animate that object instead
What do you mean? Sorry, only a few weeks into Unity dev, but decent at C#
Your object has a renderer of some kind, yes? That's the thing the animator is animating, yes?
e.g. a SpriteRenderer that is being animated by changing its Sprite
So, I apply the Animator to the children?
ah it was animator all along..yeesh
i forget it can overtake transform without Root Motion 🫣
Open the dopesheet in your animation clips and retarget the keyframed properties to the child object
Ah ok
I’ll do that a little later
Thanks @rigid island and @leaden ice for you help
Hallo everyone, does anyone know this error:
InvalidOperationException: Failed to load XRReferenceImageLibrary 'ReferenceImageLibrary': library does not contain any ARCore data.???
a quick google suggests file paths with spaces in their names might be the issue
@upper patrol
That did it. Game is now functioning perfectly @rigid island @leaden ice
Hello everyone.. I have a question real quick about nav mesh agents paths.. how does the nav mesh agent choose its path , is it always the shortest path? and if so how can I get the agent to select a diffrent path?
Hey yo so I tried making a parallax scrolling effect in unity 2D for my game and there are two layers; Maze & Glitch_BG
I made a simple code for the Parallax Scrolling and it works, however there is these weird artifacts or something... I think it's easier to just show it [Check video]
In the sides, where like the empty/transparent part is, it for some reason just stays and is not working. It is meant to be working like in the transparent parts in the center-ish area.
Thanks :)
Do you have objects with sprite masks?
No.. No I don't think so
well can you show the inspectors of the objects and how you are scrolling them?
Well this is the code that makes it scroll.... and the inspector of the bg (i tilted them later on so it looks good)
(sorry if I sent way too many photos im still learning)
why is this happening, i can download pacakge but i cant import
and seems network is ok
can you find a more detailed error message
nope
check the console
something went wrong is the only error i get
also check the !logs
Documentation
Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log
Unity Hub
Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs
yup
console is clean
try again mayhaps see if anything pops up
if you're getting an error in the package manager you should get one in console
restarted editor
btw editor version is 22.3.7f1
so i noticed there are some package error related
why is the maze renderer rotated 60 degrees on the x axis?
strange, created a fresh new project and same thing happened
log says there is a memory leak?
I have no idea how to decipher this 😭
if it happens in a new project though, there's a good bit of confidence in assuming that it's nothing to do with your actual projects
I had an issue with the package manager myself but it was because I had a windows feature disabled and it broke it
odd
sign let me try 2023 see if this still happen
sounds like you should be submitting a bug report for the version that isn't working
but what should i submit. as above shown, the only error is "something went wrong"
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
submit the logs basically
got it
unity has a bug reporter built in you should be able to just use that
you should know about it if you've ever had the damn thing crash on you
Any idea how to stop player from getting launched whenever it walks over an object? Is something wrong with my script?
Script:
private void MovePlayer()
{
moveValues = playerControls.Move.ReadValue<Vector2>();
if (isGrounded && moveValues == Vector2.zero) { EnableFriction(); }
else { DisableFriction(); }
float calcedMovementSpeed = walkSpeed;
if (isSprinting && moveValues.x == 0 && moveValues.y > 0) { calcedMovementSpeed = sprintSpeed; } // SPRINT IF GOING FORWARD AND NOT GOING SIDEWAYS
if (isCrouching) { calcedMovementSpeed *= crouchSpeedModifier; }
Vector3 movement = (transform.right * moveValues.x) + (transform.forward * moveValues.y);
movement *= calcedMovementSpeed;
movement.y = rigidbody.velocity.y;
rigidbody.velocity = movement;
}
kind of just a consequence of running up a ramp in a physics simulation
horizontal velocity becomes vertical velocity
check your gravity setting
your player has an up velocity when player touch the sphere
i just use the gravity checkmark in rigidbody
seems like it, any solutions?
i noticed you use rigidbody for player, it has simulated physics which may result into unwanted behaviour use Kinematics instead
Call it a feature and let speed runners use it to optimize their runs.
do you need to have a collider on that ball?
might look into that
i'm worried it'll be the same with any other terrain i make, so might as well fix it early
dont want my player to jump over rocks like that
ah, will probably do something that slows player down based on how much of a slope it's walking on
can anyone help me or give me a script for bounciness. like oncollisionenter add upward force?
cause physic material doesnt giuve enough bounce
this isn't the place to get free code handouts. what specific part of that are you having trouble figuring out how to do?
i dont have a clue on code at all
well if you don't know how to code, there are beginner c# courses pinned in #💻┃code-beginner to help you get started with learning
ok thanks
ok ive wrote the script below with help from a friend and it doesnt work. ive gave my player the script and a tag called OnTriggerEnter and my bouncy object a tag called BounceTrigger. when my player falls onto the bouncy object it does not bounce.https://hastebin.com/share/okitecebet.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Do you know what Debug.Log is?
So why does your code not contain any?
What do you think?
I wrote code
It does not do what I expect
I debug It
i dont think the collision is working. nothing appeared in the log
Has anyone here gotten VS Code's new Unity extension to work properly on Mac? I installed it and the required extensions along with the Unity package, and Intellisense is still failing to complete. I get this error:
[info] Project system initialization finished. 0 project(s) are loaded, and 37 failed to load.
COULD USE SOME HELP!!!
When I use target API level 33, this doesn't generate a permission pop up... it does work on older API levels
not gonna get help unless you post screenshots rather than photos
and also !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.
This is the code that generates a permission pop up on Android:
void Awake()
{
instance = this;
DontDestroyOnLoad(instance);
if (!RuntimeManager.IsInitialized()) { RuntimeManager.Init(); }
#if UNITY_ANDROID
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead))
{
Debug.Log("King of Crokinole has access to Gallery");
}
else
{
Permission.RequestUserPermission(Permission.ExternalStorageRead);
}
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
Debug.Log("King of Crokinole has access to Camera");
}
else
{
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
}
#endif
}
And it worked like a cham on API level 30 ...but not on 33
I'm having an issue where unity just doesn't allow me to disable vsync, i've tried QualitySetting.vSyncCount = 0 and force disabling it through my GPU settings but literally no matter what it will not disable
It's very simple guys;
This code:
```Permission.RequestUserPermission(Permission.ExternalStorageWrite);
Generates a pop up on Android devices asking their permission to access storage (Gallery/Camera) ...this works fine when I create a build older than API Level 33...if I create a build on API level 33...the pop up doesn't come up.
might be the right place
Will repost there , thanks!
Got a weird bug going on.
Whenever I enter and exit playtest mode my int field on my ScriptableObjects gets reset to 0.
[SerializeField] private int _ID;
public int ID => _ID;
public void SetID(int newID)
{
Debug.Log("Setting new ID...");
_ID = newID;
}
The only way to modify the ID is by the SetID method, it doesn't get called and yet the ID is being reset upon exiting playtest (the ID is not changed during it). Other fields stay as they were. Changing the name doesn't help.
And weirdly enough, if I click on my ScriptableObject file and keep it opened in the inspector, the ID doesn't get reset when exiting playmode.
Any idea what might be going on?
do you perhaps have something calling SetID in OnDestroy?
Can you show some of the other code involved?
Another thing to note: if this scriptable object is referenced anywhere else it also doesn't lose it's ID
Are any instances of this thing created at runtime? (e.g. through Instantiate or ScriptableObject.CreateInstance?
is the SO being referenced in the scene? I feel like someone tested this before, and found something along the lines if its not referenced itll just reset back to its default values. similar to how it works when using it in a build and not saving across sessions
just one of the reasons to not use this for mutable data
SetID is only called when changing something within the scriptable object files to refresh the ID's, nowhere else
show the code that does this? What triggers it?
Within OnPostprocessAllAssets if there was any change in the path containing these files, there is a call to my library which then loads all the files via Resources.LoadAll<>() and resets all the ID's using a ID generator which takes the file name as input
It's referenced in another scriptable object
Whenever I choose an enum, OnValidate() calls my library and caches the reference to that scriptable object
The only piece of code which set's the ID is this
missiles[i].SetID(UniqueIdGen.Generate(missileNames[i]));
missiles is the array created via the LoadAll call, missileNames is the array of the file names, so missile[i].name (with some changes along the way)
Weirdly it worked all this entire time and broke just now, didn't even touch anything related to that. (unless updating the editor messed something up)
But just to check it out, I'll make a gameobject which will reference each of these scriptable objects to see if it helps in any way
If it's something being changed in editor that's still a bit odd
Yeah, I referenced all of them in the scene and now the ID doesn't reset, so I guess it's kinda a solution.
Still a bit weird
That's how it looks when it's not referenced anywhere
For now I'll just keep them referenced in the scene, I rarely add new ScriptableObjects like these ones (with an ID) so it won't bother me that much
i've been having some inconsistent behaviour using Raycast, i have this node tool and i wrote a code to check if two nodes are in LOS, and if so, create a link between them
On video A, we see the correct behaviour, trying to put a node on the right side of the wall, the cylinder goes red and so does the ray to showcase that LOS is not possible.
https://i.gyazo.com/c39c488560bff80853fe230c0a85cba3.mp4
However, on video B, the LOS is somehow succeeding and not failing, despite the wall being between both nodes.
https://i.gyazo.com/8b229950f35b7690696b3eaa3624a78f.mp4
Does anyone have an idea on what could cause this weird collision behaviour? here's the raycast code i made
https://hastebin.com/share/jugodizexe.bash
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
{
Vector4 result = default(Vector4);
result.x = ((float)((int)instanceHolder % OBJECT_COLORMAP_WIDTH) + 0.5f) / (float)OBJECT_COLORMAP_WIDTH;
result.y = ((float)((int)instanceHolder / OBJECT_COLORMAP_WIDTH) + 0.5f) / (float)OBJECT_COLORMAP_HEIGHT;
result.z = 1f;
result.w = 0f;
return result;
}
what is the purpose of this function?
Doing some math on an int and returning a vector4.🤷♂️
I'm trying to make a system that allows my players to select an image on their computer to use as a skin in my game. This is my first time working with anything like this and I'm not very sure what went wrong. Actually selecting the image on my pc made it so that the font I was using, along with, somehow, basically my entire UI, became the image I chose. What did I do wrong?
public void SelectCustomSkin()
{
string path = EditorUtility.OpenFilePanel("Select image", "", "png");
if (!string.IsNullOrEmpty(path))
{
var fileContent = File.ReadAllBytes(path);
Texture2D customSkinTexture = Texture2D.whiteTexture;
ImageConversion.LoadImage(customSkinTexture, fileContent);
if (customSkinTexture.width != customSkinTexture.height)
{
EditorUtility.DisplayDialog("Select image", "The image has to be perfectly square.", "Ok");
return;
}
Rect rect = new Rect(0, 0, customSkinTexture.width, customSkinTexture.height);
SkinInfoHolder.instance.customSkin = Sprite.Create(customSkinTexture, rect, Vector2.zero, customSkinTexture.width); ;
customSkinImage.sprite = SkinInfoHolder.instance.customSkin;
}
}
public void UseCustomSkin()
{
PlayerPrefs.SetInt("skin", -1);
}
What does customSkinImage reference?
pretty sure it's referencing this big image, to preview the skin the player uploaded
Okay. Does that happen if you comment out the SkinInfoHolder.instance.customSkin part?
i commented this out and it still did the same
Weird.
Can you take a screenshot of your text components that get changed to the skin texture?
alright
it's very annoying to test because i have to fully restart unity everytime it happens because it doesn't reset otherwise
Does resetting the scene not work?
no, the UI elements of unity itself still have that image, and every font still does as well
Ui elements of unity itself..? Wdym?
unity itself becomes this image
look at the unity ui
I don't see any issue with the unity ui...🤔
Anyways, I see it's assigned as a vertex color. Does it even take a texture normal? That's weird.
this is how it normally looks
I mean, I see it affecting your in-game ui, but not the editor ui.
this is my editor UI
it changes the image to what i picked which shouldn't happen
I have a fsm with only 3 states: wandering, chasing, attacking. It currently works as I'm expecting it to but I was curious. What if a target was to spawn directly in the attacking range. In my testing, it follows the happy path of chase->wonder->attack within fractions of a second. Is there a functional or performance reason to have the fsm change the state from wandering to attacking directly instead of going through the current positive path of wondering->chasing->attacking?
Oooh.
It's very dark so I didn't notice. That's super weird.
Can you share the code where you call that method?
i managed to fix it, apparently setting this to Texture2D.whiteTexture breaks it. this makes it work
How do you access a 1D array as a 2D array again? I forgot the equation that's used.
is it i * width + j?
You access 2d arrays with [I, j]. What you shared is accessing a 1d array as if it's a 2d array.
yea that's what I was asking sorry
Then yes. Assuming i is rows and j is columns.
It depends. There might be both functional and performance impact of doing that, although both might be negligible, depending on what code you have.
In most fsm setups you'd usually evaluate one state transition per frame, so performance shouldn't be a problem. But functionally, there might be some logic you don't want executing in this situation.
For example, if transitioning between each of these states would play a certain sound, you'd hear a cacophony of sounds mixed together due to several states changing within several frames.
@cosmic rain when placing something at the width would it be exclusive? so like should i be width or should i be 1 less than width
for example in a for loop would it be
for(int i = 0; i < width; i++)
```or
```cs
for(int i = 0; i <= width; i++)
Bit field Enums and GameObject names
It should be exclusive: < width.
Since width is the count of the elements in the row and arrays start from index 0.@shell scarab
👍 thanks
I came to the same conclusion. If the player were to sneak up on the enemy, there would be no need for the chase state to execute
Also just gonna ask this here rq, does TimeoutException make sense right here to you guys?
int GetNormalRoom(bool biasDirection) // true bias direction is max value, false is 0
{
const int triesUntilAbort = 1000000;
int x, y, c = 0;
do
{
x = axisBias ? randomGenerators.level.NextInt(0, floorSize.x) : biasDirection ? floorSize.x - 1 : 0;
y = axisBias ? (biasDirection ? floorSize.y - 1 : 0) : randomGenerators.level.NextInt(0, floorSize.y);
if (++c == triesUntilAbort)
throw new System.TimeoutException("Took too many tries to find a valid room position.");
} while (roomArray2D[x * floorSize.x + y] != RoomType.Normal);
return x * floorSize.x + y;
}
you could always just create your own exception. like a TooManyTriesException if you feel that TimeoutException doesn't convey what is actually happening
true. I was taught to almost never make exceptions and ig it just stuck with me.
for some reason my i-frames iEnumerator isn't working
private IEnumerator Invincibility()
{
invincible = true;
Physics2D.IgnoreLayerCollision(8,9, true);
for (int i = 0; i < numFlashes; i++)
{
rend.color = new Color(1, 0,0,0.5f);
yield return new WaitForSeconds(iFramesDuration/(numFlashes*2));
rend.color = Color.white;
yield return new WaitForSeconds(iFramesDuration / (numFlashes * 2));
}
Physics2D.IgnoreLayerCollision(8, 9, false);
invincible = false;
}
i copied this code from my old project where i followed a tutorial
it worked perfectly there but doesnt work here
for some reason the renderer doesn't feel like working
i have the variable "rend" Serialized and i dragged in the Player's sprite renderer
Define "not working"?

i forgot
