#archived-code-general
1 messages ยท Page 335 of 1
Polygon2D Collider?
You should look into Trail renderer or Line renderer to make your life easier for your behavior
polygon collider wont scale with the screen size
is that on the canvas or game world ?
canvas
you never mentioned it was UI ๐ then just make an image with that shape and use it as a raycast ui image
google OnPointerEnter and OnPointerExit it should get you what you need
yep, my bad. i thought it was visible on the image
yep, thats what im trying to do rn but these two bars are square images that are overplaying on eachother
What do the bars looklike inidivudally?
one sec
Yeh but with line renderer and stuff like that it's not actually change the rotation
I think
Okay. And what are you planning to do with that?
i want to display the current mana when you hoover over the blue bar
and health when hoovering over the green bar
The problem is not in the way I got the position and direction
The problem is with the lightning itself
It doesn't spin to the direction he needs to
@vagrant agate
Are those 2 different images
yep
So you could just use a simple IPointerHandlers to trigger your stuff for example
yeah i know how to detect mouse hoovering
the problem is
that these 2 images overlap
^ this seems to be the solution
I'm having an issue parsing json, now that I had added "ยฃ" to one of my fields. Is there any way around this?
Whast your code? what json package do you use?
Im using Newtonsoft Json
I presume it's trying to parse a float there
It fails on this line :/
Show the JSON.
either use string instead or give an extra json property with currency or something
Ok thanks. Would it work if I wrap it in Quotes?
than it would be a string and you would need to split it to get the number out of it
right
I would prefer to do this
"Price": 123,
"Currency": "USD"
You don't win bonus points for cramming multiple things into a single value
yep, agree, thats what I would do too
Yeah, seems like a better option. Thanks ๐
Why does the z value of my object change?
code is that:
bigMeteor.SetActive(true);
float meteorPosX = Random.Range(0.2f,0.7f);
Vector3 meteorViewportPos = new Vector3(meteorPosX,2,transform.position.z);
bigMeteor.transform.position = mainCam.ViewportToWorldPoint(meteorViewportPos);
lastSkillTime = Time.time;```
its changing to 11. but how ??
ViewportToWorldPoint
make sure you account for depth
if is prospective you need nearclip plane
wdym with prospective
like if your camera is in prospective mode
Provide the function with a vector where the x-y components of the vector are the screen coordinates and the z component is the distance of the resulting plane from the camera.
i tried nearclipplane and now its changing to -9
Hi there! Is anyone using awaitables? in day to day life? Or are many using the asyncawait lib to use tasks in unity?
Just genuinely curious of what people use.
are you doing 3D ? and are you in prospective camera
im doing 2d and idk what means prospective camera
alr if you are doing 2D just pass the Z position as the position where your objects are in the world
you dont need near clip in 2D
if your world object are at z of 0 then pass , 0
my object is at z of 2 and i type 2 but its changing to -8
you have to do it after you have received the value
var viewToWorld = ViewportToWorldPoint(etc..)
viewToWorld.z = 2```
bigMeteor.SetActive(true);
float meteorPosX = Random.Range(0.2f,0.7f);
Vector3 meteorViewportPos = new Vector3(meteorPosX,2,2);
Vector3 meteorWorldPos = mainCam.ViewportToWorldPoint(meteorViewportPos);
meteorWorldPos.z = 2;
bigMeteor.transform.position = meteorWorldPos;```
so i do this
and its worked thanks.
I am having issues with hitbox detection in my fighting game; it is not frame perfect. Take a 4 frame move, sometimes it hits on frame 5 and other times on frame 4. I believe this is due to the Unity animator being non-deterministic. How do I remove this inconsistency?
the animator does not strictly operate on "frames"
if your game is running at 61 fps and your animation has 60 keyframes per second, then there will be one frame where you start and end between the same two keyframes
You can switch to "Animate Physics" on the animator to make it update in FixedUpdate. I suppose you could set your fixedupdate interval to match the target framerate.
Would anyone be able to help me with an issue I'm having with my code?
I have this script attached to a "falling platform" game object and I want it to spawn a new one in the original position after it has fallen
private void OnCollisionEnter2D(Collision2D collision)
{
if (falling)
{
return;
}
if (collision.transform.tag == "Player")
{
StartCoroutine(StartFall());
}
}
private IEnumerator StartFall()
{
falling = true;
yield return new WaitForSeconds(fallDelay);
rb2d.bodyType = RigidbodyType2D.Dynamic;
yield return new WaitForSeconds(respawnDelay);
Instantiate(platformPrefab, startingPosition, platformPrefab.transform.rotation);
Destroy(gameObject, destroyDelay);
}
So what is the 'issue'?
Sorry I completely forgot to elaborate, my bad haha
When the new one spawns it immediately starts falling (even though the player isn't on it) and it never spawns the next one
so the cycle goes: initial one when scene starts -> player lands on it -> falls -> new one spawns -> immediately falls for no reason -> no more platforms
I would presume it is falling because the rigidbody type on the prefab is incorrect
That's what I thought but in the prefab it says kinematic
But when the prefab spawns in-game it says dynamic, which I don't understand how (I guess that also explains why a 3rd one never spawns, because the coroutine never actually starts)
indeed, post the full !code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sounds like the prefab itself is dynamic
Are you sure you're looking at the prefab and not some instance of it in the scene?
Make sure you have it straight in your head which is which, and importantly - which one your spawner code references.
I double clicked the prefab from my project files to open it in the editor (so only the prefab is visible and nothing else) and double checked and it says kinematic
And I made sure to drag that prefab into the inspector field for the one in the scene hierarchy
I did notice that whenever I exit play mode, the field in the inspector gets renamed to itself, so for example the prefab is called "FallingPlatform", but the one in the scene is renamed to "FallingPlatform_1", then after I exit playmode, the game object listed in the inspector's field for the prefab also says "FallingPlatform_1", so maybe it's creating an exact copy of itself rather than an instance of the prefab, but again I don't understand why it would do that
I'll post the full code now
If a prefab has any references that point to itself, those references are updated when you instantiate the prefab
Yeah your code is doing something funny perhaps
sounds like you are overwriting the prefab reference with a gameobject reference
So if the prefab has a reference to itself, it will create a copy of itself if it instantiates that object
rather than a copy of the original prefab
Ah, yes. is this code on the prefab?
I wouldn't expect this to modify the name of anything after exiting play mode
Ohhh, that's annoying
So a prefab can't reference it's original unaltered self after being instantiated?
no
you need to get the prefab reference from another gameobject, a gamemanager perhaps
or stuff it into a ScriptableObject asset that references the prefab
But a prefab can't reference another prefab or game object right? So when the second platform spawns (using the prefab) it wouldn't know where to look for the prefab for its successor?
if you have something like a Singleton in your game you can reference that
Each platform would ask the singleton for a prefab to use
Breaking the self-reference is awkward
There is one trick, make 2 prefabs
A -> B -> A -> B -> ...
Exactly
B could be a prefab variant of A, too
which would make it identical to A
still very silly, but that'll make it Just Work once you set the two up to point at each other
hackey but effective
I think I managed to get something to work, but I'm not sure if this is a "bad" solution haha, I would greatly appreciate it if either of you could provide feedback on it
https://hastebin.com/share/gigilavuku.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not optimal but functional
Is this how you reset the object's position?
In the Awake() method, I have the following:
initialPosition = transform.position;
And then I try to reset the location through this:
transform.position = initialPosition;
However, it doesn't seem to be working as the position doesn't seem to be reset
does your object have a CharacterController on it?
are you certain no other code or components are affecting its position?
because that absolutely would work provided the code is running and nothing else is interfering
Hi, this may not be the right channel, but when I start my game it now takes 2.5 seconds to change scene, and I don't know why, I went to the Profiler and paused the live play and found the frame where it took around 2500 ms but I don't know why it's doing it, is there a way to find out exactly what is causing it? This isn't super clear
Do you guys have any recommendation for creating a timer? Any experience with System.Timer over Coroutine or Update with elapsed time check?
how accurate do you want is the question
each has their pros and cons
I am using Nakama to have a multiplayer presentation and want the client to update its values to the server every nth milliseconds
one thing I learned is using is yield waitforseconds is a bad way to do it 
(too many inaccuracies / dependencies on framerate)
if its for server stuff I'd go with probably System class
Thanks for the insight ๐ I guess I will just try how well it works. No real-time shooter here, so some inaccuracy is fine, just want to be sure to get as close as possible of knowing whats going on when.
yeah give it a try see how it works out
A very stupid question
Anyone able to help with making character not fall through map?
(my eyes are shutting down, I am doing something wrong and cannot figure out for the life of me)
You're mixing CharacterController and Rigidbody together which is a no-no
Also your MeshCollider is set to Is Trigger which makes it non-physical
As is your Plane's Box Collider
Uh really?
yes really
๐ฌ
So alright rigid body is getting deleted
Is trigger turned off
Convex is supposed to be on alongside providing contact right?
Honestly it's really sketchy having a MeshCollider on your character in any sense
especially if you're using CharacterController
With CC you basically don't want any other colliders on it at all
yes
CharacterController is a collider, you don't need another one on that object
But you do still need colliders for it to collide with
it's ok but it's probably too thin on the y axis
I would recommend making it at least .1 or ideally half a meter tall if possible.
What's the best way to replace tags like [PlayerName] in string dialogues?
I figured you can use string.Replace but i guess that would be pretty slow if you have to check for like 100 tags for every phrase
computers are pretty fast, though
When you encounter a tag, look it up in a Dictionary
hi, i have a horror gave and i need the monster to shoot object, but i tried to code someting for few hours and it doesnt woลk, can someone share some script with me or help me in another way?
It doesn't really work that way. Nobody just "has a script" that does exactly what you want
Every game is different
Like using "@" before a tag like @PlayerName
Then checking if the string contains @ and if it does extract the tag and look it up in a dictionary?
Sure
Sounds great, thanks for the help!
when your using Proton servers callbacks the override gets called when what? dose it deped on the void name like on trigger enter or is it just the name o the void, if then when dose it get called?
using Photon.Pun;
public class ServerManager : MonoBehaviourPunCallbacks
{
public override void OnJoinedRoom(){
}
}
Well, going purely off of the name, I'd say this one gets called On Joining a Room
why are you doing networking when you obviously dont understand the basics of C# ?
ye but dose it depend on the name i just got it from a tutorial and it either gets called when idk what hapens or it depends on the name
i dont thinks its such a basic question
yes it is very, very basic
Do you know what an "override" is
seriously anyone who calls a method a void should never even think about doing networking
idc what its caled just want to know if the overides activates in a specific event or it depends on the method or whaterer.
cant you just answer me?
What would be the best way to procedurally generate rocks that fit into my terrain? I need the rocks to be interactable so I can't use the built-in terrain features
not wise to start doing multiplayer at this point
raycast onto the terrain and place the rocks
Alright i will try that, thank you
you can also grab terrain data
So, it is basic. You should definitely understand the bare basics of object oriented programming before touching multiplayer
https://www.geeksforgeeks.org/c-sharp-method-overriding/
Understanding how overrides work will let you understand the documentation enough to know when they are called
thx
i fond the callback callbacks it suports and the server code thx for the override thats useful ๐
#๐ปโunity-talk this isn't a code question
Oh mb
also formulate a full sentence before hitting enter ๐
Good idea
Sorry my bad, been working since 9 am almost all day haha
all good! ๐
Hey folks, I'm trying to make a class that holds data that I'll send between objects but the type of data that will be sent is different for different things, might be a Vector3 list or a string. Are there any types that can do tbat
Can you give some more details?
a struct
if you wanna send different types of class/struct make function take in Generic
maybe explain what you want to do exactly though
Say i have a sensor object and i want it to send data to a turret. I want to create a "IP packet" that contains the destination, source, protocol, and payload to send. So the Sensor sends a Vector3 List in the payload to the turret. But what is I also want another device to send a string in the payload to a signboard with the same idea. I need a way for the payload to take multiple types of information
How does the turret know how to interpret the data it receives?
can't the thing just have same methods with different overloads of types as param?
The Turret would see the protocol and know that the data is meant for it by interpretting the protocol, then it would read the payload
in that case I'd make an abstract base class that has a field for the protocol, and then just downcast to a specific class (e.g. TurretTargetingProtocol)
or you could even just use is to check if the packet you got is the right kind
if (packet is TurretTargetingPacket turretPacket) {
// ...
}
If im reading this correctly I think Im fine on interpretting portion, but Im having trouble with how to define the payload variable, but if what ur suggesting is the solution i may just be lost
there is no payload variable here
public abstract class Packet {
public int destination;
}
public class TurretTargetingPacket : Packet {
public Vector3 target;
}
Oh so ur saying have each protocol be a class that holds its own payload
you can test if a Packet is a TurretTargetingPacket with this syntax
yes, that seems the most tractable
Thats a great Idea thank you i can work with that
If you were serializing this into data that actually goes over a network (or otherwise leaves the C# world), you would need to indicate which protocol you're using
none of that, just liking using the idea of networking inside the gamer
why do you need a generic type for this? Can't the different things use different types?
This way yeah, but the idea i was having at the time was just sending it with a class that just had a variable for destionation, source, protocol, and payload
You'd use !learn , the unity forums and the Discord server to assist in accomplishing your Unity task/game.
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have random weights set up right now but what should I do when it gets chosen? There are 4 portals. When one gets picked I want that one to be less likely to get chosen, so how would I be able to do that? Do I simply divide 1 by the number of portals available? How would I be able to eventually bring it back to its original value when others get chosen?
keep the original value stored somewhere. If you want one to be less likely then yea you're gonna have to reduce the weight of it. The amount u reduce is whatever u want. if you want to divide by the number of portals, then that sounds like a pretty significant reduction
I think I know what to do so basically when one gets chosen, the others go up by x % and the one gets chosen goes down. So Mathf.Lerp is used here since they may not have the same flat percentages. If somehow all of them get chosen equally, then the values will restore to the original(?)
i got no clue what you mean by that 2nd sentence, it sounds almost like an AI sentence ๐
. Sure you can lerp it towards something, but thats basically just gonna be subtraction or division by some amount depending how you calculate the lerp values to use.
Literally just store the original values so you can restore them whenever you want.
Thats the thing so, I want to have it restore to its original value on it's own without needing extra functions of floats. I.e.
4 portals, 4 attempts, all 4 get chosen equally
THe word "eventually" is really vague here
it's kind of unclear what you're going for
how often "choosings" happen
etc
over time? Over a certain number of choosings?
Hmm I'll try to explain what the sequence should be:
There are 4 portals
One gets randomly chosen
The portal selected is 25% less likely to be chosen over others now.
If another portal is chosen the previous chosen portals chance is increased by 25% and the most recent chosen portal is reduced by 25%
I think what I need to do involves Lerping with normalized values. Theres a flat value and a normalized value
whats stopping you from just reducing the weights by some constant factor or subtracting by a certain amount each time? Then increase by same factor.
Though if you do this a TON then eventually you're not gonna get the original values back due to floating point stuff
When you say "reduced by 25%", you mean from 25% to 0? Or you mean from 25% to 18.75%?
Sorry in order to make it simple I'll say each portal originally starts with 100% chance
that makes no sense
Acutally no I said that wrong, each portal has a flat value of 1
if there's 4, and they're all equally likely, they have a 25% chance
right
that's the weight
you really dont need to lerp here either, you're overcomplicating this when its literally just division or subtraction, based on what you want.
if you want it to go from 25% -> 18.75% then you could do it this way:
You could do this by giving each element a weight equal to the number of elements.
So 4 elements, each gets a weight of 4.
When you pick the element, reduce its weight by 1.
So 4 -> 3.
3 / 16 is 18.75%
although that math doesn't math either
๐จ
because it'd be 3/15 which is 20%
it really depends what you want >_>
when one of them gets chosen I apply a % modifier to the original value, since theres 4 objects. I remove .25f to the one thats chosen and add .25f to the rest.
Mathf.Lerp(0,maxFlatValue,normalized)
well you'd redistribute the amount you reduced by to the others
I dont think you get back the original value by doing this in reverse though.
but really this still isn';t answering the question.
WHen I have 4 items, the chance for each is 25%.
When I select one, its new chance of being chosen should be what %?
The one thats chosen is based on its FlatWeight. So one could be 10 or 20.
Actually I see the problem with my approach now, because the ones with larger weights will get reduced alot more if they get chosen
I'll try thjis
Basically the total probability needs to add up to 1 (or 100%) So whatever you take away from one item, you need to redistribute equally amongst the rest to keep the percentages as desired.
My concern is that will these numbers go all over the place as things get chosen?
so like in this example that 7.25% I took away from one needs to be split into 3 and given to the other 3 items
yes, the numbers will go all over the place.
well yea because you're using weightings that dont actually add to 100% or 1 in terms of probability
Does this mean I'll need to make min and max value for each one? I don't mind it but just askin
i don't really know what that means tbh
same
like two floats for minChance and maxChance to prevent them from going too low or high
but how does that interact with everything else
Can one of them potentially go below 0?
the chance of an individual item being chosen will always be the weight of that item divided by the total sum of all the weights
so a min/max for a particular weight doesn't actually limit the chances of it being chosen in a meaningful way, since the total sum of weights is not bounded.
no.
I actually think for a pool with N items, just starting them all with the weight N and decrementing that by 1 whenever it's chosen is the cleanest solution here.
and incrememting it (up to a max of N) whenever it's NOT chosen
Really just try this with real numbers, step away from the whole theory aspect of it.
You have 4 weightings, 25 25 25 25. You pick a portal, what should values be, how should others values react. Do they scale up? Do they stay the same? This is all just in terms of what you want the chance to be.
The redistributing the values just means if you subtract 1 from any of the weightings, you now have a probability of 24/99. The rest are 25/99. So you add 1/(num portals -1) back into the rest.
1/3 = 0.33...
24 + 25.33 + 25.33 + 25.33 = 100
You dont even have to redistribute it properly, you could just simply remove a value and add to others
Sorry what does what does N mean?
ah ok, I'm writing some pseduo code right now to try it out
and also in this case if you remove 1 from a weighting, adding 0.33 to the 3 others, you do get back to 25 for all if you select each portal once.
Now in coding you dont really because of floats, and doing this 1000 times probably will show a clear flaw
My initial goal was to not have them exceed a certain value. At a glance initially I thought these formulas would mean that the more times these get calculated the higher the numbers would go. My concern is that one might go below 0 OR the values become something like 100 from something like 25. After this it would become harder for me to read while doing debugging and such
Also, to keep things simple I started with 4 portals with equal chance. However, in the future I might want special portals that have a higher base chance than others etc
well then you need to decide strictly on how these weightings should be affected. Thats just more of a game design thought. For now, worry about getting it working and understanding the math
Alright will do, thanks!
{
int[] weights = weightTable.Values.ToArray();
int randomWeight = UnityEngine.Random.Range(0, weights.Sum());
for (int i = 0;i < weights.Length; ++i)
{
randomWeight -= weights[i];
if (randomWeight < 0)
{
return powerUpTypes[i];
}
}
return PowerUpType.AMMO;
}```
Would do weightTable here need to be sorted based on it's value here from descending or ascending or would it not matter?
thanks
Ok giving it a shot now,
{
int choiceIndex = GetRandomChoiceIndex(_choices.ToArray());
float valueToRemove = _choices[choiceIndex] / _choices.Length;
float valueToAdd = valueToRemove / _choices.Length - 1;
Debug.Log($"Chosen Index: {choiceIndex} , Value: {_choices[choiceIndex]}, Value To Remove: {valueToRemove}");
_choices[choiceIndex] -= Mathf.RoundToInt(valueToRemove);
for (int i = 0; i < _choices.Length; i++)
{
if (i != choiceIndex)
{
_choices[i] += Mathf.RoundToInt(valueToAdd);
}
}
}```
Not sure what I'm doing wrong as one value is going below 0 again
how do i sort a raycastall by distance?
look at what the RaycastAll returns. it is the same way you sort anything in an array, which you can google how to sort an array c#
i have - none of it makes sense :(
๐คทโโ๏ธ nothing really can be suggested unless you know what you're struggling with. Try just sorting an array of numbers first. Then apply it to your RaycastHit[], using https://docs.unity3d.com/ScriptReference/RaycastHit-distance.html as your number
I don't know how to sort an array of numbers and haven't been able to figure it out by googling
there are built in methods for it. You can provide it the array which you should first try with basic numbers. Then for your RaycastHit[] you may need to provide it a comparer, which basically tells it what it should be using as a comparison value
sick, thank you
should be able to get it from here :)
what's not working about my code?
That's what we'd like to ask you. What doesn't work and what makes you think so?
Provide details in your message instead of linking to reddit.
the reddit post is the code i used. the second link is my implementation.
also, i see the problem but not the solution. it uses ARRAY.sort, but there doesn't seem to be a list.sort
Did you look at the list documentation?
can't find unity doc on lists
i promise i'm trying 
got a solution from another discord
well first thing, why does this need to be a list?
you should really try to get more familiar with c# basics. lists and arrays are as beginner as it gets
I'm getting a NullReferenceException when I try to add a newly constructed object to a list--```cs
_actionList.Add(new Utilities.InputBuffer(_playerInput.currentActionMap.FindAction("Jump")));
public class InputBuffer
{
public readonly string Name;
private float _timer;
private float _duration;
public InputBuffer(UnityEngine.InputSystem.InputAction action)
{
Name = action.name;
Debug.Log($"{action}");
//action.started += Action_started;
}
private void Action_started(UnityEngine.InputSystem.InputAction.CallbackContext obj)
{
_timer = _duration;
}
public bool Queued
{get{return _timer <= 0;}}
}
the debug.log in the constructor is getting called, so I don't think there's a problem with the object itself
this is line 216
DAMMIT
I forgot to initialize _actionList
The list reference is null
I'm trying to create a script that "digs" into the ground in a spherical shape by transforming the mesh used to make up the ground. However, once I reach a certain depth, the mesh doesn't move.
I'm pretty sure the reason is because the vertices that have been warped are so far apart that the function meant to find the vertices doesn't see them, but I don't know how I would go about fixing this. So how can I fix this and is this even the right method to use to get what I want?
good evening, sorry if this is silly buy im using an interface to write my enemy take damage code and im wondering why my enemy character doesnt die, heres the code for the damage function and the interface code
public void Damage()
{
//Health -= 50;
for (currentHealth = 100; currentHealth > 0; currentHealth -= 50)
{
if (currentHealth <= 0)
{
Destroy(Enemy);
}
}
//currentHealth = currentHealth - 25;
}
public abstract class EnemyStructure : MonoBehaviour
{
public int currentHealth;
//public float speed;
protected abstract void Update();
protected virtual void Attack()
{
Debug.Log("Enemy Class: Attack Method Called");
}
}
he doesnt die after 2 hits
does anyone know whats wrong?
What is the point of that for loop?
before i used to have it randomly written in the function and realized everytime the function is called it resets the health to 100
so i put it in the for loop so that it doesnt
but im sure thats wrong lol
i just cant call it outside the function
or i can but its weird
The loop is definitely not what you want
Someone here used photon before?
I have 2 players connected to 1 server, works fine, they can use the movement script perfectly well, but the sphere (body) falls to the ground and disapears for the other player (only visually) it still works well after that... but its wierd
Damage should just reduce health, then immediately check if it is 0 or less
ah okay
Hello, I would like some help. I want the order in layer jump to work correctly, and there are no parts where it doesn't work. I've attached the script for you to verify it thoroughly.
using System.Collections;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Sprite[] walkSprites;
public Sprite idleSprite;
public Camera mainCamera;
public int minOrder = -1;
public int maxOrder = 1;
private SpriteRenderer spriteRenderer;
private int currentSpriteIndex = 0;
private bool isWalking = false;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.sprite = idleSprite;
}
void Update()
{
Vector3 moveDirection = Vector3.zero;
// Check for combined key presses
if ((Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)) || (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.S)))
{
StopWalking();
return; // Stop movement if both A and D, or both W and S are pressed simultaneously
}
// Handle individual key presses
if (Input.GetKey(KeyCode.W))
{
moveDirection.y += 1;
if (!isWalking)
{
StartCoroutine(WalkAnimation());
}
}
thank you :))
public void Damage()
{
//Health -= 50;
currentHealth -= 50;
if (currentHealth <= 0)
{
Destroy(Enemy);
}
//currentHealth = currentHealth - 25;
}
like this?
the order in layer jump to work correctly
What?
secund part
if (Input.GetKey(KeyCode.S))
{
moveDirection.y -= 1;
if (!isWalking)
{
StartCoroutine(WalkAnimation());
}
}
if (Input.GetKey(KeyCode.A))
{
moveDirection.x -= 1;
spriteRenderer.flipX = true; // Flip sprite horizontally
if (!isWalking)
{
StartCoroutine(WalkAnimation());
}
}
if (Input.GetKey(KeyCode.D))
{
moveDirection.x += 1;
spriteRenderer.flipX = false; // Don't flip sprite horizontally
if (!isWalking)
{
StartCoroutine(WalkAnimation());
}
}
transform.position += moveDirection.normalized * moveSpeed * Time.deltaTime;
// Update camera position to follow the center of the sprite
if (mainCamera != null)
{
Vector3 spriteBoundsCenter = spriteRenderer.bounds.center;
mainCamera.transform.position = new Vector3(spriteBoundsCenter.x, spriteBoundsCenter.y, mainCamera.transform.position.z);
}
// Adjust sorting order
int sortingOrder = Mathf.RoundToInt(transform.position.y * -100);
sortingOrder = Mathf.Clamp(sortingOrder, minOrder, maxOrder);
spriteRenderer.sortingOrder = sortingOrder;
if (moveDirection == Vector3.zero)
{
StopWalking();
}
}
private IEnumerator WalkAnimation()
{
isWalking = true;
while (isWalking)
{
spriteRenderer.sprite = walkSprites[currentSpriteIndex];
currentSpriteIndex = (currentSpriteIndex + 1) % walkSprites.Length;
yield return new WaitForSeconds(0.071f); // Adjust animation speed as
!code
Use paste sites for long code (the first one alone was already a bit too long)
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Copy the url and paste it here
okay
But also, describe what is happening and what you want to happen, because
the order in layer jump to work correctly
Doesn't make any sense
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and... yea, i use chatgpt 4o for the codding XD
and, in #๐ปโunity-talk the photos to the errors
Delete all that there and post it here
Anyone here knows about AssetBundling? How do I keep the files I download from a cloud bucket permanently, like how mobile games let you download them initially with a small size then download the remaining files after. Or does the app cache it by default if its from cloud?
where? on the server? or on another page?
The same channel as the rest of your question...
#๐ปโcode-beginner , not #๐ปโunity-talk
This channel
I don't know why you posted it to a different channel at all
Sure. But the pictures are pretty clear
You want to be in front of the wall on one side, and behind it on the other
I don't do 2d games like that, so I am not sure, but someone will know and can help
Yes, it's just that when I'm on top of that wall, I put myself back, I don't know why.
ho, okay, no problem, thx for help me to the channels and the code pages ๐
Not even me, it's my first video game, I try to do everything myself, even the sprites, that's why they look so bad
I was also thinking of leaving it like this, and putting something like a blur to see through the walls, in the process the character would be seen
Hey, I wrote a modular save game-system that uses this interface and a ScriptableObject as a data holder.
public interface ISaveDataItem
{
public void SubscribeToSaveHandler();
public void SaveData(SaveDataScriptableObject data);
public void LoadData(SaveDataScriptableObject data);
}```
Now I'd love to have it like this instead, but this obviously does not work with interfaces:
```C
public interface ISaveDataItem
{
public void SubscribeToSaveHandler()
{
SaveHandler.OnLoadData += LoadData;
SaveHandler.OnSaveData += SaveData;
}
public void SaveData(SaveDataScriptableObject data);
public void LoadData(SaveDataScriptableObject data);
}```
Is this just the trade-off that comes with interfaces or is there a way to easily force all instances of the interface to subscribe to the static events?
You're going to want to use an abstract class instead
But this is odd in my opinion. I would assume you get all instances of ISaveDataItem and call the methods manually, not through an event?
Either that or you have a general singleton that has all persisting data
Yes but some classes already are inherited so that is not an option.
That is possible but what's wrong with subscribing to a static event?
It's just the way the data is saved. How do you determine what object goes to which interface implementation?
Sadly an interface can't work like this in Unity so you'd have to do it manually in each constructor/awake method
Hm ok. That's what I thought but wanted to double check. Thanks!
Another way would be source generation
Or lastly, run a method at the start of the game that fetches all instances through reflection and then hook them up from there 
Modern interfaces do have some support for what you want but idk if that works specifically
Not 100% sure what you mean but all my game systems have one point of entry that should handle all references and everything.
well the point of interface is so that you can directly call these methods as needed. You would store a collection of these objects like List<ISaveDataItem> and then call Save/Load. Right now you actually dont even need the interface. You could create a class like this
public class Something : MonoBehaviour
{
void Start()
{
SaveHandler.OnLoadData += LoadData;
SaveHandler.OnSaveData += SaveData;
}
public void SaveData(SaveDataScriptableObject data);
public void LoadData(SaveDataScriptableObject data);
}
The only part of the interface that looks used is SubscribeToSaveHandler
This actually does work, it's called default interface methods.
But, I would strongly suggest to not use it. Most people consider this C# feature a mistake.
It does, DIM is a C# 8 feature and Unity supports C# 9 for a few versions now.
Putting aside the code, conceptually what you are trying to do is that "a train should tell the train station to start driving itself" which is really not how it should work. Train station should be the one instructing the train, not the other way around.
Huh did my last message get blocked? well the message i tried replying to was deleted but i wrote "my class currently does everything your interface is capable of doing. Im just giving an example of why your interface isnt neccessarily needed."
I deleted my message because I think I understood your approach ๐
yooi
Library\Bee\artifacts\WebGL \build\debug WebGL_wasm\buildjs: undefined symbol: ReleaseChannel (referenced by top-level compiled C/C++ code)
any idea about this error??
using photon
ah i just meant that discord actually blocked my message, shook the screen, and told me i cant send it lol
usually it still sends
Ok. You might be right, I am often not sure who should be the one calling the shots. So you would be in favor of caching all instances of the interface/class and then looping through them when saving/loading?
That's fine, explicitly listing out all the things you want to loop through is also fine.
My thought process often is: I don't want to use FindObjectsOfType<T> too often for obvious reasons. I also sometimes don't know which objects will be there at runtime. Using static events seems to be the most flexible solution. Or not?
well im sure none of the suggestions here was gonna be FindObjectsOfType ๐ . One simple change could just be like
public class SaveHandler
{
List<ISaveDataItem> saveItems = new();
public void RegisterSelf(ISaveDataItem saveItem)
{
// add to list
}
}
and then instead of invoking the event, just loop through and call SaveData or LoadData. Also just realized its static but you probably can adjust for that
Hello, I'm trying to achieve this kind of screen wrapping so that it looks continuous instead of simply teleporting the player to the other side. I found a tutorial that uses this script and 3 cameras but I cant seem to get it to work. For some reason my right camera is showing on the left of the screen and its still snaps.
public class CameraCountinuousScreen : MonoBehaviour
{
private float absScaleX; //abs scale of the sprite to get correct values
private float colliderSizeX;
private void Awake()
{
//current scale of our transform
absScaleX = Mathf.Abs(transform.localScale.x);
colliderSizeX = GetComponent<BoxCollider2D>().size.x;
}
void Update()
{
if (transform.position.x < Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x - (colliderSizeX/2 * absScaleX))
{
transform.position = new Vector2(transform.position.x + Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x * 2, transform.position.y);
}
if (transform.position.x > Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x + (colliderSizeX / 2 * absScaleX))
{
transform.position = new Vector2(transform.position.x - Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)).x * 2, transform.position.y);
}
}
}
In this case SaveHandler would need to be a singleton or else how would I be able to call RegisterSelf() if I don't neccessarily have a reference?
you can use a singleton yea or the same way you reference SaveHandler.OnLoadData, by using static. I just didnt write static in my example above
Thanks
I guess the script works and its just a issue with the camera setup
nvm i cant figure out
I made some progress by setting the side cameras as overlay and adding it to the stack on the main camera. But now if I go too far in any direction it just snaps again, and I'm not sure why because it should snap only when it goes through the side the first time, if it makes sense
is there a way somewhere to render scene view in editor to a 4K texture with a single button?
alternatively use scene camera to take a screenshot
Hi i have a menu panel on my game project and im trying to add a PointerEnter event trigger to my UI Button to drigger an animation but when i assign the PlayButton to the proper field and from the dropdown i try to assign the proper method (OnPointerEnter) it does not appear in the dropdown. how do i fix this
Also here is my code
using UnityEngine;
using UnityEngine.EventSystems;
public class PausemenuPlayButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public Animator animator;
void Start()
{
if (animator == null)
{
animator = GetComponent<Animator>();
}
}
public void OnPointerEnter(PointerEventData BaseEventData)
{
animator.SetBool("MouseIsHovering", true);
}
public void OnPointerExit(PointerEventData BaseEventData)
{
animator.SetBool("MouseIsHovering", false);
}
}
here i don't see the OnPointerEnter method...
That is not the way the Ipointer interfaces work, they are called from the EventSystem
oh can you explain further ?
it's simple, you dont need to assign them to anything, the event system sees that you have subscribed and calls your methods when they fire
ok so the whole event trigger component in my play button game object is unnecessary?
yes
so remove this
sorry im asking dumb questions but i wanna make sure :DDD
and then the scene need a event system game component?
so here i dont have an avent system so i need to add that to the scene and it handles all automaticly?
All scenes need an Event System if you are using UI
ok and when you create a canvas it creates a event system automatically i just deleted it cuz im stupid :DDD
that was, indeed, not advisable, Unity did not add one for no reason after all
thank you this helped a lot :D
next time, instead of just doing random shit, go and read the docs first
Good advice :D
i'm confused, Main camera is in the middle, why are there dots around the left camera and lines around the right camera. Also when I play it shows the right camera even if the main one has priority
not a code question. #๐ฅโcinemachine ?
so now the event system automatically knows when im hovering on top of the button but how do i make the button do its hovering animation (button pulsates larger and smaller) when im howering on top of it. Any tips on that?
https://docs.unity3d.com/2017.3/Documentation/ScriptReference/UI.Selectable.DoStateTransition.html
this is legacy UI but I'm sure TMP has something similar
Thank you :)
must I reiterate. The docs are where you should be looking to answer questions like this
got it
Hey. I wrote an editor script to add a button to my script and the function of the button is it gets the colliders size and set the value automatically. the button works well and the values changes when I press is, but the problem is when I Play, the values resets back to before I press the Auto-Align. How can I save the values that I change in Edit mode via script?
Pretty sure you have to use EditorUtility.SetDirty(...) on the object/component after you change the values
You can also use Undo.RecordObject before changing the values if you want undo/redo functionality
what!? It didn't work when I tried it just now, but after you said it, I tried it again and it worked
ooh, what I tried was SetDirty(gameobject), but the right way is SetDirty(this)
thanks
Quick question about disabling physics. As Physics.autoSimulation = false; is obsolete, I can`t really find the solution to not calculate physics entirely.
Okay, so you cant disable it entirely, just stop the calculation when set to script? Thanks, wwas not sure, this is the right doc I found ๐
Okay, thanks ๐ Just trying to crank out as much performance as possible right now ๐
Hey, got this code over here thats meant to make the player move around the map alongside rotate the model at appropriate directions. The rotations work fine but the corresponding asdw keys are not working properly. Any ideas how to fix this?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f; // Movement speed
public float sprintSpeedMultiplier = 2f; // Sprint speed multiplier
public float sprintKeySpeed = 10f; // Speed when sprint key is held down
private void Update()
{
// Get input for movement in the horizontal and vertical axes
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Get sprint key input
bool sprintKey = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
// Calculate movement direction based on input
Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput).normalized;
// Modify movement speed based on sprint key input
float currentSpeed = sprintKey ? speed * sprintSpeedMultiplier : speed;
// Apply movement to the player
transform.Translate(movement * currentSpeed * Time.deltaTime);
// Rotate player based on camera's forward direction (optional)
if (movement != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(movement, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
}
}
}
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ah I see thanks.
Did you write this code yourself? And you should just learn to debug.log your stuff and understand every line of that code. If you do, you will get what is missing. Especially about the GetAxis part
Nope, I am not a programmer simply trying to get through an programming unit.
More intrested in Cyber Security aspects of computing.
Yeah, thats also the easier part about it structures ๐ ๐
Cyber Security without knowing anything about programming, how does that even work?
Don't know.
Nice talk, cya ๐
hey, I have
public abstract class DialogueAction : ScriptableObject { }
and
[CreateAssetMenu(fileName = "UnitJoin", menuName = "DialogueActions/Unit Join")]
public class UnitJoinDialogueAction : DialogueAction { }
when i create asset for this it looks like this
why is there a "none mono script"
When you are working with Unity Scriptable Objects you should derive from Scriptable Object. public class UnitJoinDialogueAction : ScriptableObject
i need it to be derivering from DialogueAction
DialogueAction is a ScriptableObject
If UnitJoinDialogueAction is not in its own file with the same name as the class, you might need to do that
ah yeah, i forgot that unity works like this
thanks ๐
I've created a script that spawns the player at the position of the Scene View in Unity. I did everything and it works fine but I wanna make something better.
private void OnDrawGizmos()
{
if (SetToView)
{
SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView.in2DMode && sceneView != null && !Application.isPlaying)
{
Vector3 _Pos = sceneView.camera.transform.position + offset;
if (_Pos != centerPosition)
{
centerPosition = _Pos;
Gizmos.color = CrossColor;
Gizmos.DrawLine(centerPosition + Vector3.down * crossSize, centerPosition + Vector3.up * crossSize);
Gizmos.DrawLine(centerPosition + Vector3.left * crossSize, centerPosition + Vector3.right * crossSize);
EditorUtility.SetDirty(this);
}
}
}
}
what is does is basically gets to position of the scene view when it changes and later I apply the position to the players position on Awake().
what I wanna do is make it a bit more optimized because it saves the centerPosition every single frame that position is changes. but I want it to only save (SetDirty) the position when I press the Play, just before the game is started and before the awake.
I used EditorApplication.isPlayingOrWillChangePlaymode before SetDirty.
I just wanna make sure if is there a better way of doing it
this
if (sceneView.in2DMode && sceneView != null
is illogical
if I make my script as IPointerClick event for EventSystem - do I need to mark my background image as raycast target if it's a child of empty gameobject with this script to trigger it? Am I right that EventSystem triggers it's callbacks from child objects of trigger too?
im working on a grappler in my 2d game, and just followed a tutorial where the guy sets the grapple to pull you in a certein length that you can choose. put i dont want that. so is there a way to make it so the grapple length to be set to the mouse position? because what i have tried has not been working
I think I remember reading that somewhere, but shouldnt be too hard to test
Showing code would make it easier to help
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrapplingHook : MonoBehaviour
{
private float mousePos;
[SerializeField] private LayerMask grappleLayer;
[SerializeField] private LineRenderer rope;
private Vector3 grapplePoint;
private DistanceJoint2D joint;
// Start is called before the first frame update
void Start()
{
joint = gameObject.GetComponent<DistanceJoint2D>();
joint.enabled = false;
rope.enabled = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast(
origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
direction: Vector2.zero,
distance: Mathf.Infinity,
layerMask: grappleLayer);
if(hit.collider !=null)
{
grapplePoint = hit.point;
grapplePoint.z =0;
joint.connectedAnchor = grapplePoint;
joint.enabled = true;
joint.distance = mousePos;
rope.SetPosition(0, grapplePoint);
rope.SetPosition(1, transform.position);
rope.enabled = true;
}
}
if(Input.GetMouseButtonUp(0))
{
joint.enabled = false;
rope.enabled = false;
}
if(rope.enabled == true)
{
rope.SetPosition(1, transform.position);
}
}
}
this is the code for the grapple
So do you want to limit the grapple distance to the mouse position?
yes
This doesn't seem to cast the grapple from the player, it just checks if there's an object where you clicked ๐ค
What type of 2D game is it? Like what perspective
platformer
i would use
-origin: Character's position (or hand position)
-direction: mouse world position - origin
-distance: magnitude of direction
If you want to cast it from the character and not be able to grapple inside a wall
Those are the parameters for the Physics2D.Raycast
sorry if this seems simple, im kind of a beginner
since when is that C# syntax ?
what?
what you posted as code is not code
check the code above thats what i had the syntax is what osmal gave me to help with my problem
what Osmal posted is pseudo code, you are supposed to use your initiave and fill in the blanks (or non code bits)\
Sorry, even a raw beginner should know that 'Character's position (or hand position)' is in no way valid code
if you do not then I suggest you learn C# basics
yeah i figured that part out
didnt know that other parts
i know c# basics
its the other part
Even with C# basics, you would know "magnitude of direction" is not valid code either.
Anyway, you can always look at the docs for actual code examples:
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
thank you
Hi, I'm introducing Assembly Definitions in my project however I'm encountering some issues.
I've referenced most of the assemblies I use but I can't seem to find an assembly corresponding to System.Collections.Generic so I'm getting this error: The non-generic type '...Authoring.Baker' cannot be used with type arguments
Is there an Assembly Reference I'm missing or is it something else ?
it's unlikely you're missing System.Collections.Generic, are you sure you're not missing a reference to whatever assembly "...Authoring.Baker" or one of its parent classes is in?
When you duplicate a gameobject in the scene, is there any event that gets called inside unity that tells you, this object is "new"? I am trying to keep consistent guids for gameobjects but when copying lets say a prefab with an id predefined, i want to assign a new guid, otherwise all prefab instances would use the same.
Theres the InstanceID, which will be unique for every instance in the scene:
https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html
This is not consistent between sessions so you wouldn't gain much by storing it, but you could check for differences to know if two objects are unique instances of the same prefab
I don't think you are required to reference specific internal namespaces, do you?
This error is weird
ah, that's a decent idea: you could write your instance ID to a variable in Awake
Either way the error is shown because it did find System.Collections which contains non generic types
I hadn't thought of that before. That might actually be enough to detect being instantiated
Hmmm, that sounds like an intresting approach, thanks ๐ Will look into that
The Parent Class of my Baker Class is located inside the Unity.Entities assembly which I reference. However for some reason functions/classes that are part of the Unity.Entities package aren't recognized
The Assembly Definition that encompasses the relevant scripts
I am trying to use Splines, but when I try to find the nearest point on the spline i keep getting a point of (0, 0, 0) then suddenly it switches to a different point as seen in the attached photo. It will be like A for some period of time then suddenly switch to what B says (B changes as the object moves).
Follow Path logic (currently only get nearest point for the PID Controller) --> https://hatebin.com/tbfalfiege
Object movement logic (for testing) --> https://hatebin.com/cbgqqzufnh
one important thing to note is that you get a position on the spline -- not in world space
notice that GetNearestPoint takes an ISpline, not a SplineContainer
Try transforming this point into world space
(using the transform of the spline container)
i did find that out, however it gives me the point on the spline of (0, 0, 0) for a while then suddenly switches
You also need to transform your world-space position into the spline's space when passing it in
I did not do that
I presume your world space position winds up behind way behind the start of the spline in its own space
hence all the [0,0,0] results
that makes sense,
Anything that uses a SplineContainer is world-space; anything that uses a Spline is in the spline's own space
splineContainer.transform.TransformPoint goes from local to world, and InverseTransformPoint is the opposite
ok thanks, I will have a look into that, that does seem to be the issue, world/local points
I found this to be confusing when I was learning to use Splines!
a spline doesn't exist in the world on its own, which is why anything that uses a spline is done in the spline's own space
a spline container does exist in the world
the knot coordinates listed in the spline container are in the splines coordinate system it seems, corretc?
ok, i get what is going on now, seems like a weird way to do it.
it's equivalent to how you animate the local rotations of an armature's bones, not the world rotations
otherwise the animation would change (and go horribly wrong) as you rotate the armature
ahhh yes ok got it
@heady iris Thank you for the help, I'm going to go and get this all working hopefully ๐
So I heard about this thing called "marching cubes", but I'm not really sure I understand it. What I understand is it's supposed to be a bunch of vertices that each represent a cube that can be turned on and turned off via some kind of binary code, but I don't understand how that code is calculated or how it determines what cubes are turned on and which are turned off
there are quite a few tutorials about the process; have you followed any of them?
I also don't really get it yet, but I also haven't tried to actually implement it
I tried. This is the extent of what I understand about it
catlikecoding has a series on marching squares
the first part talks about the bitmasking
All you're doing there is looking up a mesh based on which vertices are filled in
with four vertices, you get 16 configurations
(including some with rotational symmetry)
I presume that, for marching cubes, you have 8 vertices, and thus 2^8=256 possible configurations
(exponential growth gets big quickly)
for marching...lines, you'd have 2 vertices with 4 configurations
Hello! I need help understanding why OnTriggerStay2d is being called twice.
Here you can see when my player is standing on the edge of the composite tilemap collider, the OnTriggerStay2D is called twice, but it is find when the player is standing in the middle of the composite tilemap collider
(Using Outline mode gets this behavior. using polygon mode yields the exact opposite behavior)
OnTriggerStay is called every frame that the colliders intersect
I know that, as you can see it's being called twice in the same frame
the debug logs are collapsed and show (2) on the same exact fixedtime
Probably because two things with this script on it are colliding with each other
you debug no useful information. what about other?
ah ok
my bad it was indeed 2 colliders on my player
though i do have another question now, shouldnt this prevent calling ontriggerenter twice?
and is there a way to have a collider ignore/not be detected by all trigger colliders?
okay nevermind i figured out my own solution, thanks guys!
what would you say is better for detecting if a character is grounded in a sloped 3D environment:
- a collider using OnTriggerStay
- raycast detecting the ground
- spherecast detecting the ground
last option
or checksphere
what are its advantages vs ontriggerstay?
haven't had much luck googling the differences
ontriggerstay is not as reliable
plus you would have to make a sepearate collider just for it
or a variable being brought over from a different script in my case I guess
doesn't handle multiple surfaces as well, you don't get details about ground you hit (if you need slope angles etc)
you want overlapsphere
I just need to check if there are any ground colliders whatsoever, not doing something to each one in an array
spherecast doesnt work if the cast originates inside of another collider
unless you are to say cast it above your pivot downward
seems to be detecting it just fine. just needs some radius tweaking
It can work but written on the docs it even says
Notes: SphereCast will not detect colliders for which the sphere overlaps the collider. Passing a zero radius results in undefined output and doesn't always behave the same as Physics.Raycast.
I was just dealing with a similar issue I couldn't melee something with my guy because I was too close with it cast
and the fix to that is to use both overlap and spherecast
yeah I recall a while ago having to switch it to overlap for similar reason
checksphere also works for simple usecases (when you don't care about raycasthit)
I'm already running into issues visualizing the best way to detect the ground at any rate
such as where exactly I should be positioning the sphere and how large it should be
thats what gizmos/physics debug window is for
yeah I'm just trying to think of this exactly:
let's assume I cast the sphere like this
I think it would work in theory, but where should I be casting it so my character doesn't just float a bit off the ground?
alternatively, if I do this...
would I need to do a cooldown when the character jumps so they can't jump again right after that?
thats why you make the offset and size serialized values in the inspector
so you can play around with it in test mode, see what fits best your character
I tried that, but I think the gizmos were not being updated in real time
either that or I screwed up the code
prob 2
void OnDrawGizmos()
{
Gizmos.DrawSphere(groundCheckPos, sphereRadius/2);
}
don't mind that /2
I got the size but called it the radius and realized that later
groundCheckPos is what exactly ?
a position that should roughly land the sphere here ^
where do you set it though
in update.
playerHeight = groundCollider.size.y;
// (...)
groundCheckPos = groundCollider.transform.position + groundCollider.center;
groundCheckPos.y = groundCheckPos.y + (playerHeight / 2) - 0.1f;
groundCollider is a box collider
playerHeight is a float being set in the inspector
ah, wait, no it isn't. I changed that to use groundCollider's bounds
hey guys, is there a way of applying shadows to a tmp text? cant seem to get it working. i believe its because the text material has color set to HDR but i cant find a way of disabling it, any ideas?
no really a coding question, but on the text component you can open the shader options at the bottom to mess around with colors and other options
not too sure about shadows though as that may be something not included in it
AFAIK the material it uses is unlit by default
you'd need a shader that takes lighting into account
yeah ive tried every shader that comes with tmp package
even the extras
but every color is locked to HDR
it's actually like 3 lines of hlsl code to do if you do want to edit the whole dang shader
actually would probably break a bunch of stuff
oh..
legacy text and a custom shader is what I'd do
Does anyone think they can help me with Developing a Wall placement and Room Building System like in Sims 4?
@swift falcon
but isnt this the Code Channel?
Like I can understand objects like furniture, but I am a bit confused as how I can generate walls from dragging one point to another
oh you mean extruding the walls ?
You need to code such a system but it's a very big task. I would learn about the Mesh class first to generate meshes
Yeah I think so
yeah pretty much you need to learn building meshes
I think the older ones were easier to replicate then new one
older building meshes?
But isnt sims 4 tiles too?
the wall building to me looks like it builds a mesh/modifies it as you pull the arrows n whatnot
its still grid based ofc
well do you know any ways I could start with the basics of one closer to Sims 1?
lots of boolean operations probably for walls and windows
founds this https://github.com/francot514/FreeSims
might help
You can do without full booleans but you do have to do some complex procedural generation
yeah thats beyond what my monkee brain can handle
Hey I'm really new to unity (the code-beginner channel is being used) and atm I have a 2d game with a gameObject that has a few children with sprite renderer components and one tmp text.
I have the script set up to make it fall and spin and that all works but I can't figure out how to make it clickable.
The simplest way is to use OnMouseDown
some raycasting method usually
A slightly better way would be to use the event system's IPointerDownHandler - which will allow itself to be blocked by UI elements, among other advantages.
ok and to use the onMouseDown I need to attach a collider to the object right? Is that all it takes or do I need other stuff with the camera raycast things? I googled it and got a lot of different answers
yes it needs a collider
I assumed you had one already with your description of it falling and stuff
It only needs a collider for OnMouseDown
raycast logics usually need a collider to detect something 'hitting' it
for IPointerDownHandler you need other things too, but that's a different approach
no lol I just moved it all manually and once it's y was below a point I just deleted it.
so if I have a lot of cards falling and they might overlap would the onMouseDown approach be fine? Like does the IPointerDownHandler do something important in the context of my simple game?
The materials on Images don't seem to create a new instance when you access them.
Compared to renderers.
Does anyone have any tips for making code/features more modular, or can point me in the direction of resources that point these out? I'm currently running into some tightly-coupled-mess issues which I want to prevent in the future
Well on renderers it's optional. Material or sharedMaterial
Doesn't seem to be optional on images.
Gotta create my own.
Yes not very consistent but as you say you can duplicate and apply new
usual stuff, events
Better off showing some code and then asking what you can do to improve it
hi
How does this boundsInt not contain the vector3 position (0,0,0)???
It's an exclusive upper bound
that's necessarily because otherwise it'd be impossible to create a bounds that contains nothing
I see
problem solved thank you my friend
Hi, i am trying to make a teleportation script, but it doesn't want to work, it works for one frame, you can actually see the destination, but then you are snapped back, if i send someone my code, or my project can someone please try and fix it?
Are you using a CharacterController?
just show the !code and setup so theres no guess work. Could be a few reasons causing this
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yea
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@spring creek is that an issue?
yea with a character controller you need to disable it, teleport it, then enable it.
ah, how can I do that?
via .enabled and set it to false, set the position, then set enabled to true
MyCharacterController.enabled = false
Destroy(gameObject);
Destroying assets is not permitted to avoid data loss.
why would this ever result in that error? It is a script on a gameobject. The script does have references to scriptable objects and such but just destroying the gameobject itself shouldnt result in an error thinking im wanting to remove an asset from my library right?
do you have a snippet of the code?
I think I got it actually, just wrong order of instantiating something that exists on a prefab
I added this to the chessboard script, this just shows where i added the history panel stuff, Now im trying to to figure out how to make it look right in the UI like scroll view, any suggestions?
public GameObject moveHistoryPanel;
public Text moveTextPrefab;
private List<string> moveHistory = new List<string>();
private void OnMakeMoveServer(NetMessage msg, NetworkConnection cnn)
{
// Receive the message, broadcast it back
NetMakeMove mm = msg as NetMakeMove;
// Add move to history
AddMoveToHistory(mm);
// Receive, and broadcast it back
Server.Instance.Broadcast(msg);
}
private void OnMakeMoveClient(NetMessage msg)
{
NetMakeMove mm = msg as NetMakeMove;
// Add move to history
AddMoveToHistory(mm);
}
private void AddMoveToHistory(NetMakeMove mm)
{
// Add move to history list
string moveString = $"Team {mm.teamId} moved from ({mm.originalX}, {mm.originalY}) to ({mm.destinationX}, {mm.destinationY})";
moveHistory.Add(moveString);
// Update move history panel
UpdateMoveHistoryPanel();
}
private void UpdateMoveHistoryPanel()
{
// Clear existing text objects
foreach (Transform child in moveHistoryPanel.transform)
{
Destroy(child.gameObject);
}
// Add move text objects
foreach (string move in moveHistory)
{
Text moveText = Instantiate(moveTextPrefab, moveHistoryPanel.transform);
moveText.text = move;
}
}
what do you mean make it look right? whats specifically wrong with it
not showing up in the scroll view...
I get this error when I try to move MissingReferenceException: The object of type 'TMPro.TextMeshProUGUI' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object. Parameter name: data
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Bindings.ThrowHelper.ThrowArgumentNullException (System.Object obj, System.String parameterName) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Internal_CloneSingleWithParent (UnityEngine.Object data, UnityEngine.Transform parent, System.Boolean worldPositionStays) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Transform parent, System.Boolean instantiateInWorldSpace) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Transform parent, System.Boolean worldPositionStays) (at <240ff6271d47469a95269de220922c38>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Transform parent) (at <240ff6271d47469a95269de220922c38>:0)
MMM.Chessboard.UpdateMoveHistoryPanel () (at Assets/Scripts/Chessboard.cs:1081)
MMM.Chessboard.AddMoveToHistory (NetMakeMove mm) (at Assets/Scripts/Chessboard.cs:1067)
MMM.Chessboard.OnMakeMoveClient (NetMessage msg) (at Assets/Scripts/Chessboard.cs:1048)
NetMakeMove.ReceivedOnClient () (at Assets/Scripts/Net/NetMessage/NetMakeMove.cs:54)
NetUtility.OnData (Unity.Collections.DataStreamReader stream, Unity.Networking.Transport.NetworkConnection cnn, Server server) (at Assets/Scripts/Net/NetUtility.cs:41)
Client.UpdateMessagePump () (at Assets/Scripts/Net/Client.cs:93)
Client.Update () (at Assets/Scripts/Net/Client.cs:67)
added a debug, the error now is Move text prefab is null. Cannot instantiate move text objects.
```private void UpdateMoveHistoryPanel()
{
// Check if the moveTextPrefab is null
if(moveTextPrefab == null)
{
Debug.LogWarning("Move text prefab is null. Cannot instantiate move text objects.");
return;
}
// Clear existing text objects
foreach(Transform child in moveHistoryPanel.transform)
{
Destroy(child.gameObject);
}
// Add move text objects
foreach(string move in moveHistory)
{
TMP_Text moveText = Instantiate(moveTextPrefab, moveHistoryPanel.transform);
moveText.text = move;
// Add click event listener for move replay
moveText.gameObject.AddComponent<MoveReplayClickHandler>().moveString = move;
}
}```
this is a really hard way to read the error, but the error is quite clear on whats happening in its first sentence.
as for stuff showing up in the scroll view, have you tried doing this first manually and seeing if they show up at all?
without the move history panel the moves show up in debug
I think i might have forgotten to name the move text prefab right
well i cant see your entire setup, but i dont know what you mean by "name the move text prefab". If something is null, you likely just didnt assign it a value yet.
Are you using AI also?
no ai for game yet... watching a video on minmax algorithm
No, i meant are you using AI to code.
if you have a couple minutes, I have my own server, I can live stream my screen????
I code from reading and watching videos
no, quite literally just look at the component and see if you assigned a value to the prefab
I have it set for a tmpro, but i want it to be a scroll view, which isnt tmpro, so i have to recode i think??
I suggest you dont copy the code then so much, and try to actually understand whats happening. Because the issues you are describing, like null or MissingReferenceException are really quite beginner. Yet you seemingly have a lot of code since that error was on line 1081
if moveTextPrefab is null then you probably want to assign it to a prefab containing text, that moves. not a scroll view
Hey all. I'm looking to see if there is a way to set the aniamtion clip in the AnimationWindow through script. Some google fu led me to this "https://forum.unity.com/threads/change-default-clip-in-animation-window-for-animator.1482060/" but I cannot seem to get it to work properly. Any help would be awesome. Thanks!
Are you trying to set it from an EditorWindow?
i notice the link you posted also does use .animationClip, is there something specific that wasnt working?
Yes I'm attempting to set it from another EditorWidow script. Whenever I try to select say idle or fidget it always defaults to intro.
are you selecting a valid animation clip? Like one that exists already in the dropdown menu
otherwise there isnt really much that can go wrong here
I should be.. and I didn't think so either. Will have another go when I'm not so dang tired. Thanks @lean sail ๐
I quickly tested from an editor window as well, just by making a field for the animation clip and dragging in one from the assets folder which worked. If the issue is different then id be interested in knowing what it was
whenever you get around to solving it
Will report back when I get back to it.. thanks again!
or just use LFS. its up to you
Ive recently been dealing with a similar issue but for textures and audio files, the suggestion I ws given was to use git for just code files and engine-specific files (like scenes, prefabs, scriptable objects, etc) and all imported assets like models, textures, audio (in your case, plugins) should be a part of a secondary cloud storage like Box or something that is intended to support more space, git (at least the free plan) supports I think 2GB or 4GB for your entire project, so files that weigh 100+ MB will eat that limited space, LFS offers an additional I think 1 GB or 2GB of storage for those large files, but its not really a "solution" imo since it will fill up fast... The downside of a second cloud storage though, is you lose any asset references that prefabs or scene objects might have had, unless you re-reference them by their file paths and push their file paths with your commits, that means those assets need to be imported in your project before you open the project, cant say either is an ideal approach but its the one ive been suggested recently
Hee, I had a code issue but it included photon, I posted it in #archived-networking but maybe it should be in here? Not sure ๐
public class WaitForAnimation : CustomYieldInstruction
{
private Animator animator;
public override bool keepWaiting => animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1;
public WaitForAnimation(Animator animator)
{
this.animator = animator;
}
}
Anyone know why it is not waiting for the animation to finish in my Coroutine
What coroutine?
public IEnumerator ShootCoroutine(EntityType entityType)
{
hasPicked = true;
Entity target = GameManager.Instance.GetEntity(entityType);
if (target != null)
{
target.animator.SetTrigger("Pressed");
if (entityType == this.entityType) target.animator.SetBool("Is Self", true);
else animator.SetTrigger("Aim At Target");
yield return new WaitForAnimation(target.animator);
}
yield return new WaitForSeconds(1f);
}
Can you try logging what animator.GetCurrentAnimatorStateInfo(0).normalizedTime would be when keepWaiting is called?
you are not really waiting for anything. jyou just setting the animator and then continue
something bigger than 1...
Can you try updating keepWaiting and call Reset() before returning the boolean if it returns false?
Just taking reference from this, idk if this would fix it
Or actually, do you have the boolean wrong? I think it should be > 1
omg...
Or I'm wrong, I'm not exactly awake
they would have to be resetting something, the method by itself does nothing. but i think the current < 1 is correct because you want to keep waiting while its not 1
I also wonder what indicates to you that this isnt working, because this coroutine does nothing after waiting
it does something, it really isn't relevant enough...
public IEnumerator ShootCoroutine(EntityType entityType)
{
hasPicked = true;
Entity target = GameManager.Instance.GetEntity(entityType);
if (target != null)
{
target.animator.SetTrigger("Pressed");
if (entityType == this.entityType) target.animator.SetBool("Is Self", true);
else animator.SetTrigger("Aim At Target");
yield return new WaitForAnimation(target.animator);
bool isBullet = GameManager.Instance.Shoot();
if (isBullet)
{
target.animator.SetTrigger("Hit");
target.Die();
yield return new WaitForAnimation(target.animator);
}
bool keepTurn = (target == this && !isBullet);
if (entityType == this.entityType) target.animator.SetBool("Is Self", false);
target.animator.SetTrigger("Normal");
animator.SetTrigger("Normal");
hasPicked = false;
GameManager.Instance.StartTurn(keepTurn);
}
yield return new WaitForSeconds(1f);
}
Ah i see
doesn't go beyond 1
doesn't even get there
have you checked that the animation is fully playing? If its going between 0 and this 0.0166.. then that might indicate its constantly playing the start of one
You might even want to store the AnimatorStateInfo and then check if its the same as the initial one.
Ah i see what's going wrong
it stops because the animation it was originally playing finished
so i would have to wait like 0.01s extra
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
I havent experimented with this much, because it looks like a pain in the ass but maybe you could just use StateMachineBehaviour instead of trying to fight the animator and guess when its finished. Since you might even run into cases where its playing the same animation again and then it thinks it never finished the first one.
You just need to tie into that OnStateExit
or have a animator event at the end of the animation
kinda dumb to hardcode your anim duration into your code
I think animation events are even worse ๐
hmmm, makes things easier...
I'll check it out
woah woah, imagine calling something dumb ๐ฆ
You might really wanna do testing with what i linked, because I havent used it other than once for testing. I saw something online about OnStateExit not being called if it loops but that was an old thread.
Also i dont know what they meant because you didnt code the animation duration anywhere, normalized time is fine.
not you
but like
lets just say I worked with programmers whos entire code is like that
Animations in general are pain and imo there is no right way to have animations, besides not having them.
i enjoy animations a lot more when im just doing my logic alongside them, rather than trying to tie into animation events.
It also lets me just easily swap out animations, because i never had an event associated with it in the first place. All I declare in editor is when in the normalized time something should happen (ex: at 0.5 or 50% through the animation). Then start a timer and do my logic after that timer reaches 50% of the total length, which i also use a speed multipler for so the animation takes the total length i declare in editor.
I usually have some timer sync'd to my animation time when I play it so I just refer to that
I was trying to use those animation events earlier, but I needed it to execute in late update I think? And, I wasn't too sure how to accomplish that.
I just ended up using Animation Events as I am in a rush
makes my code messy but eh, I'll take it
that's the spirit
Hey, dont know if this is the right channel, but TMP has completely broken on me, here are all the characters showing up wrong, and the errors
The font asset seems to be broken, im not sure how i would fix it though
This one of the pains of Git, I had same issue. Use LFS or just use an easier source control system like SVN which I prefer ๐
Try reimporting it. Does sound like it's something to do with slicing up the character atlas.
or use the font asset creator thing
So are marching cubes just for random mesh generation or are there ways to build specific shapes with it? I'm still not really understanding it or even if this is something I want to explore
It doesnt have to be random, you can give it any kind of 3D grid you want as input
It's just often used with random/procedural generation, if it is used
So if I'm trying to create a specific shape, would it even be worth it to look at this?
That's up to you - depends on your needs. If a regular terrain isn't enough and you need stuff like caves and overhangs then it is good
What I'm trying to do is have a character remove a semisphere shape from a mesh so as to dig a hole
Yeah was about to say, if the mesh needs to be edited by the player then that is one of the advantages of marching cubes
Otherwise you could just 3D model the terrain
So this IS something I should be looking into then?
Because the way I have it set up right now is it just pushes the vertices around and that eventually reaches a point where I just can't dig any deeper because the vertices are too far apart from the player and one another
It's a good option for player-modifiable terrain
Thats how 7 days to die does it, and a bunch of other games (astroneer?)
The downside of marching cubes is you end up with very limited angles - it is still a bit boxy. Are you not limited to flat, vertical and 45 degree slopes?
Think I remember seeing some implementations where the density grid is based on floats instead of bools, allowing for smoother transitions
That gets more complex though
Yeah, I remember seeing something like that in Sebastian Lague's video. It's one of the few parts of the video I understood
Good old Seb
Ok, so I think I'm getting the theory a little better. The idea is that the actual configurations are these isolines (or I guess isoplanes in the case of cubes rather than squares) that try to separate the corners of the cube that ARE turned on from the ones that AREN'T and these isoplanes become the mesh triangles you want to create. That sound about right?
From there I assume then that you assign each of these corners a float value between 0 and 1 to fine tune where you want the isoplane to place its point as it's otherwise going to place it in the middle between the two points
[SerializeField] private float mouseSensitivity = 100.0f;
[SerializeField] private Transform playerBody;
private float xRotation = 0.0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
Why does my camera movement stutter when I look up and down? But not left and right.
You should not multiply mouse input with Time.deltaTime
And after you remove that, you need to make mouseSensitivity a lot smaller
oh alright
still does not feel really smooth tho compared to horizontal rotation
its like when it goes above 0 on x rotation it stutters when I look up and down
are there any rigidbodies involved?
no
I want to know what's the object that teleport when I teleport with the VR the exact object
You can check if it's an input problem by replacing mouseY with a constant
like, say, 30
or maybe use 25 * Mathf.Sin(Time.time * 3) to make it go up and down
Anyone know what makes UI Graphic component a registered collider with a canvas raycaster? I want a minimal collider without using that class on my UI, but for now I just use that and stop it drawing anything!
so I'm just figuring this out myself (like, starting yesterday)
there is an interface called ICanvasRaycastFilter
if you implement it, it adds a method that the graphic raycaster calls
I think that method gets called as long as you're inside the bounds of the Graphic (which Image derives from)
correct you can modify that function to do say circular collision which helps when they only have rectangular!
but if I only implement that then I get no collision - if I make it a Graphic I do
Does anyone know, if you can check if a using System.Timers timer is running? reading through the docs right now, but maybe someone knows it already
Oh, I guess it might just be as easy as .Enabled
So I had a number of errors that my tired brain just couldn't compute.
First I had a list of the animation clips that I set to the anim override controller earlier in the script. This list became invalid once I removed the prefab from the scene to instantiat later.
Next I tried just pulling clips from the prefabs animator runtimeanimcontroller. Which would have worked, but I was calling the anim window update and then swapping my prefab to another model to preview. I just needed to call the anim window update after I swapped in my new prefab and then we were good to go.
Don't code while tired.. ๐ช
Hello guys, I could use some advice on my system design for Units.
I'm trying to implement an Unit with a state machine for controlling the macro state the unit is in(chasing, fleeing, roaming, etc..), and a command queue to deal with animations and concrete actions(moving, attacking, etc..). Also trying to enforce composition as much as i possibly can.
I already have some components, like a movement component, a health component which are all standard C# objects.
I already have the state machine and the command queue.
My commands are all scriptable objects and all units should be able to just reference them and call the functions passing themselves as arguments.
My big problem is actually checking and accessing these components from the unit argument inside their functions.
I tried adding a dictionary to my units like this
public enum UnitComponents { Movement, Attack, Health, Mana, Loot}
public Dictionary<UnitComponents, Object> components { get; private set; } = new Dictionary<UnitComponents, Object>();
but it does feel like just a band-aid in an otherwise pretty solid system.
Just creating variables in the Unit also doesnt seem too great, because not all units will have to move, or will need health...
this is my current movement command
public IEnumerator Execute(Unit unit)
{
if (unit.components.ContainsKey(Unit.UnitComponents.Movement))
{
NavMeshMovementComponent unitMoveComp = (NavMeshMovementComponent)unit.components[Unit.UnitComponents.Movement];
unitMoveComp.Move();
unit.animator.CrossFade(moveHash, 0.1f);
yield return new WaitWhile(unitMoveComp.HasReachedDestination);
Logger.Log("Move Finished", this, LogType.CommandLog);
}
}
which is not working just yet because i cant convert from object.
Wouldn't your enemy SO contain SOs of command units
If that's what you're aiming for. Such that you have range enemy AI and stuff
Otherwise the prefab route and populate an Enemy prefab with commands seems fine
got a strange situation... In my game I move position of objects at certain times during the game. When I run it in the unity editor this works fine but when I do a build the positions aren't updating. Any ideas?
yeah, thats kinda of the idea. the problem is getting the componets of what each unit can do in the actions. but ill probably create a superclass Component and then just cast for each different type and check if it exists
The difficult part is joining all of that togheter
lots of things could be wrong.
First thing to do is check the player log for errors
Second thing to do is start adding Debug.Log to your code to print some relevant information and check the player log to see what they print.
msot of the time differences in build come from:
- Execution order issues (script execution order is not guaranteed across platforms)
- Framerate-dependent code
Ideally you group components in tiers and/or weighted chance. It's less about getting them (as they should be on the SO anyway) and more about what stage/chance to execute them.
If they are in low hp sub state/conditions then you should have a field on the SO for what unit should be checked when that state is entered
it's probably the frame rate dependent code. What I'm seeing in the editor is if I go frame by frame then the object updates to the new position I want for one frame... but then reverts back to it's original position which I don't want it to do thereafter. But if I just run it without stepping through frame by frame it seems to work (most of the time). But then when I build it it doesn't work at all
But I can't see in the code what is making it revert back to it's original position. It doesn't seem like there's anything telling it to do that
Well I can't see your code at all. So if you'd like some help I would recommend sharing it ๐
I will share it. Just finishing another issue then will share
how do you paste it in? I think someone sent a link before so the format looks right
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ideally use a paste site
ok will do this shortly
ok ready to do this... Shall I just paste the whole script? it's around 130lines... @leaden ice
ah wait it didn't paste the whole thing
A paste site
same problem guys, does anyone know how to solve this?
ok one sec
I guess, selfsigned is not enough to be used anymore
I don't get it.... sorry haha never tried this before
I used the paste.ofcode site
it pasted it to a webpage
how do I get it from there to here in the correct format?
ohhhh right
oh! that's bad news! testing would be som much worse now, another other way taht I can run wss and make it talk to https?
is that link working?
it's complaining about how the certificate was signed, rather than about whether or not it trusts the certificate
an HMAC is used to produce a digest of data with a secret key
Does the error provide any more information?
okay so the line I'm having trouble with is line 123. Where I take an object from the list objs and position it in a new position. It positions it in the new position for one frame and then reverts back to it's original position. I can't see what is making it revert back to it's original position though
Thats why I added "guess". I ran into several issues on my project becuase https selfsigned was not allowed in unity anymore. But as you explained, you might be right and it could just be the setup ๐
it should reject the certificate if it isn't trusted, but I would expect an error about the lack of trust
I can explain more what the code is trying to do if that helps
What components does that object have?
looking at the source code, it looks like the code only supports SHA1
goofy
SHA1 is busted, and it's probably no longer the default used by openssl et al.
it has a box collider, rigidbody, controller script, and animator script
the controller script it using rigidbody.velocity etc. When I comment out all of the code on rigidbody movement then the repositioning works correctly
https://github.com/mono/mono/issues/21565
You'd have to tell openssl to generate a cert using SHA1
which is bad, because SHA1 is bad (relatively)
nope
got it
yeah...๐ถ
Thanks bro @heady iris
I would've guessed that the animator is the reason, but if you think the rigidbody controller is causing it then show that script
ok one second...
https://paste.ofcode.org/Kfm7TvHvWSugvQZk28yWry this is the shark controller script
when I comment out the section 'public void FixedUpdateShark1()' then the repositioning in the other scripts works
I'm just testing it again now to make sure
ok so it's 100% the 'public void FixedUpdateShark1()' section in the controller script causing the issue. I just did a build with that section commented out and all of the repositioning works perfectly. As soon as I have that section running in the code then the shark moves to the new position for one frame... but then reverts back to it's original position after which I don't want it to do
but I don't get how... I'm only updating the rigidbody velocity in the 'public void FixedUpdateShark1()' section. I'm not updating it's position....
But velocity might drive your transform to a specific position. You should start adding line by line affecting your velocity and see where it starts to break
Do you have "Interpolate" enabled on the rigidbody?
If so, setting the position of the transform will not work. The rigidbody will update the transform's position and rotation every frame.
You need to set the position of the rigidbody directly.
(if Interpolate is off, then the rigidbody only updates the transform in each fixed update cycle, and it synchronizes transforms before that happens, afaik)
setting the position doesn't try to interpolate (so you won't see a few frames of the rigidbody flying across the screen)
you should generally never directly set the position or rotation of an object with a rigidbody on it, since you're bypassing the physics system
it's because I coded it when I was brand new to coding. Only just appreciated the conflicting with physics system issue very recently. It's annoying because the shark objects don't even need a rigidbody. So it's made everything way more difficult using one. I think it'd be a lot easier if it didn't have a rigidbody right i.e. to rotate it and move it the way I want it to move
ya, it's not something that'si mmediately obvious
Why do they not need a rigidbody?
Did you only add one because you need collision messages?
yeah... and the player itself has a rigidbody
only one of the two objects need a rigidbody right
for collisions to work
A non-kinematic rigidbody can hit static colliders, as well as another kinematic rigidbody
It would be reasonable to use a kinematic rigidbody (with Interpolate off) and to just set the position every frame
Can I use rigidbody.MovePosition as a workaround in the meantime?
both calling MovePosition and setting position won't actually do anything until the next physics update
so keep that in mind
What you can also do is call Physics.SyncTransforms() immediately after modifying the shark's position
I think that will get it to teleport properly (and immediately)
but I'm not sure on that
I'll try that
I think MovePosition in fixedupdate is taking interpolation into account
I'm going to try a few things in next few minutes to see if I can get it working for the time being
From docs, only setting the position of rigidbody directly will teleport
Right
I need to refresh myself on the exact differences (I keep forgetting how each way interacts with other rigidbodies that get in the way)
Same ๐ thats why I am just relaying the doc info here ๐
you're completely right on the interpolate thing! As soon as I turn it off everything works. Now to just try to get it to work with the interpolate for the timebeing as I need interpolate on to keep the rigidbody rotations looking smooth
I think you can just keep interpolation on, but when you teleport the object use rigidbody.position instead of transform.position
going to try this now!
you guys are awesome! Thanks so much! I spent most of my day trying to figure this out and was getting nowhere. Didn't even do any work in my actual job today because of this lol. Released a game on steam this morning and this was causing big issues so now can update it with the fix. Thanks all!
Hey, guys. I'm new to unity, I need a little help with one question. I'm using the OnPointerEnter method to change the sprite when the player hovers over it:
public void OnPointerEnter(PointerEventData eventData)
{
transform.localScale = originalScale * scaleFactor;
}
but my sprites are not square, and this method does not work with Polygon Collider and it turns out that the sprite shrinks when the cursor touches the invisible area around the sprite. The only thing I've come up with is to check in the Update method for each item to see if the cursor coordinates match the Polygon Collider coordinates, but I think this is obviously not the best solution, is there any way to fix this, thanks for your help in advance.
What are you trying to accomplish here?
And what kind of object is this
UI.Image
So you could set this to a desired value to avoid the hit test on invisible areas
Why it's not exposed in inspector is beyond me 
the more you expose, the more possiblities for missing setting a value you create
UI elements should not have colliders. Colliders are for world space objects.
So - what are you trying to do again?
Idk what you mean by that it's literally settable in code Why not float in inspector lol
UI Elements should use the pointer interfaces. The Event System will properly ignore transparent pixels
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.IPointerEnterHandler.html
In a larger team, there is always human error possible changing values accidentally or what not. With not exposing, its set to 0 for everyone and you can overwrite it scriptwise without giving others the option, to change it again.
Also your image needs to be set to read/write. Even more possibilities to make it not work
but .. but... when things don't work its fun to fix.
bruh, im tryna code in Unity, but VSC doesn't show me available classes and hints (without them i'm lost) and VS can't open the project
what do yall code in?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
if you want to use VS. Close VS and your project then delete the .sln and .csproj files in your project
hold on, like, rn i have only 1 monoscript, but if i had multiple, i'd have to delete all of them???
the .csproj files not the .cs files. Please read what I write
ah. Theres a diff. Right, my bad
I have an array of objects they should be arranged in the form of several tabs I used for this GridLayoutGroup and Panel and then took sprites one by one from the list and displayed them on the screen assigning their value to the prefab Image, and for these objects I just wanted to make animation on mouse-over and also the ability to create a copy of them and move it, something like an infinite source of resources in the game.
for the animation on mouseover you can just use the existing Animation transition mode for Button
for creating copies - I guess you mean dragging and dropping? That is well-trod ground where you can find lots of tutorials. I think the best thing though is to use e.g. Graphics.DrawTexture while dragging until you drop it somewhere
So just replace the Image in the GridLayoutGroup with a button and assign all sprites to buttons, right?
The Image is part of a Button
Selectable also works, instead of Button
Button is just a Selectable with an onClick event
Hi guys I had an issue with the job system
I have 2 functions that get triggered through buttons
Yeah, I know, I almost misspoke.
Thank you so much, sorry for possibly stupid questions
one of them starts a job that has to run infinitely.
When I run the other function however, the job immediately ends
is that normal?
Inside the job I call an api that returns an http stream
the other function is a regular http response
wdym by "job" exactly?
oh unity job system?
Unity jobs are not meant to run infinitely. They're meant to be pretty short lived
Also - jobs can't deal with managed objects which are present in almost any HTTP framework
It would be very unusual to make HTTP requests within a job
I did. The error persists
show your external tools window
thats fine, now the complete VS window with the solution explorer open
Ok the diff is that now it opened the file, but the classes are still not loaded - they're not green. And the project is unbrowsable.
that looks like you dont have the Unity workload installed in VS
!code
๐ Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry
use a paste site
the game i am making is like slender 5 pages spawn around the map I wanna make a mode where you see how long you can last I want a page to spawn if one is collected how do I make this code do this?: https://hastebin.com/share/awewuxicom.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Nuget package? Or connect to Unity?
this
Make a custom class called Pages, and everytime you instantiate one add it to a List<Pages>, each Pages class would hold a boolean of its collected state that you could access from your page spawner class
read the instructions for using Visual Studio. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
ok thank you
But i already have it
right click the file and find Reload with Dependencies
In Solution Explorer window
where it says "Assembly Csharp"
Go back to here, and in the Solution Explorer on the right, right-click the "Assembly-CSharp" project and select "Reload With Dependencies". That should fix your issue.
oh, seems to finally work. Thatks!
ok now i have a new problem - can't figure out how to make something that can play a menu song indefinitelly. However, i have an ITIN part and a LOOP part of the song. I wanna make the script make the INIT part play first and than when its done loop the LOOP part.
I have a code that does it, but it either does it late
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
audioSource.loop = false;
audioSource.clip = track1;
audioSource.Play();
}
// Update is called once per frame
void Update()
{
if (!audioSource.isPlaying)
{
audioSource.loop = true;
audioSource.clip = track2;
audioSource.Play();
}
}
Or early
// Start is called before the first frame update
void Start()
{
Run();
}
// Update is called once per frame
void Update()
{
}
private async void Run()
{
audioSource = GetComponent<AudioSource>();
audioSource.loop = false;
audioSource.clip = track1;
audioSource.Play();
await Task.Delay((int)Math.Floor(track1.length * 1000));
audioSource.loop = true;
audioSource.clip = track2;
audioSource.Play();
}
Are there any resources or rules of thumb for architecting my code if I want to leave the option open to implement co-op multiplayer in the future?
Don't use singletons for the stuff relating to a player.
why is this in an async function ?
wouldn't it be better to just check the current time /timeleft on audiosource, in update to switch to next one ?
That's what their first solution is doing
its using isPlaying
Try stopping the source before switching to the new clip: audioSource.Stop(), see if that fixes it
audio mixer would be good for this