yes, I'm already storing it, but my logic is broken, and the clients only have display and minimal information about objects, while the server has logic that is stored on the host. Therefore, I need a separated option, and I need to know where everything goes. If you have written what I need, you can send me the documentation. After reading the netcode documentation for gameobject, I haven't found a solution, and I may be blind.
#💻┃code-beginner
1 messages · Page 771 of 1
Allow player to choose file directory
Simply put, I need something like this
public class Client : NetworkBehaviour
{
[Rpc(SendTo.Server)]
public void SendMessageToServer(string message)
{
}
public void RecieveOnClient(string playerName)
{
}
}
public class Server : NetworkBehaviour
{
private void ReceiveOnServer(string message)
{
if (string.IsNullOrEmpty(message)) return;
string messageToClient = await serverRelease.ReleaseEvent(message);
SentdToClients(messageToClient);
}
[Rpc(SendTo.ClientsAndHost)]
private void SenddToClients(string response)
{
}
}
There's a multiplayer sample aka BossRoom you can tear apart
I have a player gameobject where i'm trying to make it spawn in the center of the generated map (100x100). Whatever i did (from what i know) in my code it ignores to spawn at the center (which should be 50-1-50). It always goes to the location what is written in the player transform 15-1-15. Im lost for now 🥲
show instantiation code
OK, I hope this helps.
I mean it is an official unity project by the devs of netcode for gameobjects
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player == null)
{
Debug.LogWarning("No Player GameObject found with 'Player' tag!");
return;
}
// Spawn in center - try to find an Air tile
int centerX = worldWidth / 2;
int centerZ = worldHeight / 2;
// First, try to find a walkable spot near center
for (int radius = 0; radius < 10; radius++)
{
for (int x = centerX - radius; x <= centerX + radius; x++)
{
for (int z = centerZ - radius; z <= centerZ + radius; z++)
{
if (x >= 0 && x < worldWidth && z >= 0 && z < worldHeight)
{
if (worldGrid[x, z].IsWalkable())
{
player.transform.position = new Vector3(x * tileSize, 1f, z * tileSize);
Debug.Log($"✅ Player spawned at: ({x}, {z}) - Distance from center: {Vector2.Distance(new Vector2(x, z), new Vector2(centerX, centerZ)):F1} tiles");
return;
}
}
}
}
}```
what is the log printing?
Also does your player object have a CharacterController component on it?
If it's an agent too you usually want to use the teleport method it has as it can rubberband you back to previous location
My player has player controller and mining controller.
This is the log, according to the log everything is good but my character is still at 15-1-15.
show the inspector of your player object
after that, the code of those scripts may be relevant
There you go
Ok and your player controller script, can you share the code?
using UnityEngine;
public class PlayerController3D : MonoBehaviour
{
[Header("Movement Settings")]
[SerializeField] private float moveSpeed = 3f;
[SerializeField] private float rotationSpeed = 10f;
private Rigidbody rb;
private Vector3 moveDirection;
void Start()
{
rb = GetComponent<Rigidbody>();
// Lock rotation so the player doesn't fall
rb.constraints = RigidbodyConstraints.FreezeRotation;
}
void Update()
{
// GET Input (WASD / Arrow Keys)
float moveX = Input.GetAxisRaw("Horizontal");
float moveZ = Input.GetAxisRaw("Vertical");
// Moving in 3D area (Y stays 0, we move over the ground)
moveDirection = new Vector3(moveX, 0f, moveZ).normalized;
// Rotate character in direction (optional, later for animations)
if (moveDirection.magnitude > 0.1f)
{
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
void FixedUpdate()
{
// Movement via physics
Vector3 newVelocity = moveDirection * moveSpeed;
newVelocity.y = rb.linearVelocity.y; // Keeps gravity/vertical speed
rb.linearVelocity = newVelocity;
}
}
player.transform.position = new Vector3(x * tileSize, 1f, z * tileSize);
Debug.Log($"✅ Player spawned at: ({x}, {z})```
your log says "spawned at x, z" but the actual code is multiplying by tileSize
Debug.Log($"Player position is: {player.transform.position}"); would be a good idea after you move the player too
I would just remove the for looping atm and just reposition by exact points
Didn't work, tried it multiple times.
yes, deleting tilesize doesn't change anything either. It is as if the code is ignoring my giving player.transform value
Did you try the Debug.Log thing I said?
it's more likely you are changing it but some other system/script is changing it right after on that frame
If it prints the right position after that then either:
- You have some other code or component moving the player after this code does
- You're misinterpreting the numbers in the inspector and it has a parent object
I would even go as far as removing the rigidbody but doesnt seem like the problem
but not that I've not done that before ;p
All my player code is the only one i sent you which is the PlayerSpawn. It might be a parent object problem, how can i check that?
does your player object have a parent or no
The numbers you see in the inspector are the object's local position. If the object has a parent that is translated, rotated, or scaled away from the origin, the local position will not be numerically equal to the world space position
It doesn't
then it's not that
See if adding Physics.SyncTransforms() right after the position setting code helps
and/or setting the Rigidbody position instead of Transform
this fixed it
now it does spawn at the given log location
setting the Rigidbody position directly instead of the Transform would also do it then
it's best to avoid Transform modification for Rigidbodies in general. This is also a bit problematic:
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);```
I'd recommend rb.rotation instead
(what you have right now will break interpolation)
How come the rigidbody is overruling the transform location of that which i don't understand.
Alright i'm looking into that.
Damn, now my character runs smooth. I love that thank you!
Ah so it was the rigidbody. I know that messing with the position could rubberband it, but surprised the rotation is actually tugging at it too
Anyone use Cinemachine here? I'm trying to figure out a way I can make an "enemy" I can drag out, and whenever the player interacts with the enemy, it'll switch to the CombatCam, but I don't wanna attach a new combat cam to every single enemy and would rather just use something that connects each enemy to a specific combat cam
would i just use a Cinemachine brain for this?
Any way to get these tooltips to show up from the summaries?
Feels a bit much to constantly duplicate the text between the tooltips and the docstrings
public class Director : MonoBehaviour
{
[Tooltip("All gameplay modules in the game. Non-sequential.")]
[field: SerializeField]
/// <summary>
/// List of all gameplay modules in the game. Non-sequential.
/// </summary>
public List<GameplayModuleData> _gameplayModules = new();
/// <summary>
/// Public readonly getter for all gameplay modules in the game.
/// </summary>
public List<GameplayModuleData> GameplayModules => _gameplayModules;
/// <summary>
/// The gameplay module that should be loaded upon game start.
/// </summary>
[Tooltip("The gameplay module that should be loaded upon game start.")]
[field: SerializeField]
public GameplayModuleData StartingModule { get; private set; }
}
Is there a way to get the text from the current TextMeshPro page?
Tried finding it in the documentation and on the forums but had no luck with that so far.
what exactly are you trying to get?
I'm trying to get the text that is on the current page
Putting a debug statement with the text value of TextMeshPro only gives me the first two lines, skipping the third one, even if I've changed the page
Alright, thank you
I don't think u can customize XML doc, but may be the other way around is possible
Tooltips are meant to show inside Unity editor
Hey I'm trying to do things with Unitys spline package. I see no option to get the t-value of the splines knots. Which means I'd have to loop over the knots, get their position and then use spline.Evaluate to then do things with the result. This feels like a waste of computational power, is the value accessible somewhere? It's not in the BezierKnot struct but I also can't find a function in SplineUtility and the likes.
Hi , quick question , maybe not such a short answer, I am new to Unity and game dev in general and am looking to start a pet project myself for a small remake of a much loved old PS2 game.
I have been doing the C# coding myself and have got to the stage where I need to start thinking about a damage system for units - Before I start it I wanted to check if this was perhaps the correct thing to do or should I be looking for and implementing a pre written script at all?
sorry if any of that comes across as if I have no clue what I am doing....As I dont 😄
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
I think the answer to the question depends on what you are trying to achieve. I'd scan the asset store for potential fitting assets, but also check out YouTube as there are some good tutorials that can help you get started.
The asset store probably gives fine solutions, but tweaking them might be a lot of work.
Tutorials can only get you far, depending on your skill level and what your goal is there might be a lot of work to do to get the system to do what you want it to.
Sorry if that is not the most helpful answer, but the question is kind of broad 😅
Thanks for the fast reply!
And don't be sorry was actually the exact guidance I needed for what was indeed a super broad question xD! I suspected I would need to either create it or amend an existing one - really I just wanted to ensure there was not some default script for RTS style damage systems.
In short I just need to create a script to handle:
- Instances of Damage
- A damage table to calculate the actual damage a unit takes.
- Armor/Resistance modifiers
- Event hooks and callbacks for animations and such.
And I imagine actually much much more , I will have a look to see if anything fits in the asset store and look into amending it to fit , in the meantime Its youtube time I guess!
how to fix my float var getting like 9th digit inaccurate while calculating? it should only go to first digit after point
Floating point error is a part of life. Why do you feel like it needs to be "fixed"?
What's the context and the end goal?
because it fricks up my hud
That's what number formatting is for
i want to see values like 0.5 on hud, not 0.50
Display it in your HUD with an appropriate number format
Check the code example
TMP is irrelevant
hello i have a problem im creating a 2d game and i added a weapon system that shoots projetiles but the projetiles are not showing if im playing i added sprit render and all the stuff but its not working
can someone help pls
Do the game objects themselves spawn? Does sprite renderer have the correct sprite? Does prefab (if you're using one) shows the projectile correctly?
We need to see your scene setup and your code
Code would maybe be useful too. I'm guessing it might have something to do with incorrect projectile rotation
using UnityEngine;
using System.Collections.Generic;
public class ProjectileController : MonoBehaviour
{
// Settings
private int damage;
private float speed;
private Vector3 direction;
private float lifetime;
private bool piercing;
private int maxPierceCount;
private GameObject hitEffectPrefab;
// State
private float lifeTimer;
private int currentPierceCount;
private HashSet<GameObject> hitTargets = new HashSet<GameObject>();
public void Initialize(
int dmg,
float spd,
Vector3 dir,
float life,
bool pierce,
int maxPierce,
GameObject hitEffect
)
{
damage = dmg;
speed = spd;
direction = dir.normalized;
lifetime = life;
piercing = pierce;
maxPierceCount = maxPierce;
hitEffectPrefab = hitEffect;
lifeTimer = lifetime;
currentPierceCount = 0;
}
private void Update()
{
// Movement
transform.position += direction * speed * Time.deltaTime;
// Rotation
transform.rotation = Quaternion.LookRotation(direction);
// Lifetime
lifeTimer -= Time.deltaTime;
if (lifeTimer <= 0)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter(Collider other)
{
// Ignore player
if (other.CompareTag("Player")) return;
// Ignore already hit targets
if (hitTargets.Contains(other.gameObject)) return;
// Hit enemy
if (other.CompareTag("Enemy"))
{
hitTargets.Add(other.gameObject);
ProcessHit(other.gameObject, other.transform.position);
// Check piercing
if (piercing && currentPierceCount < maxPierceCount)
{
currentPierceCount++;
Debug.Log($"[PROJECTILE] Pierced! ({currentPierceCount}/{maxPierceCount})");
return; // Don't destroy
}
// Destroy projectile
SpawnHitEffect(other.transform.position);
Destroy(gameObject);
}
// Hit wall
else if (other.CompareTag("Wall") || other.CompareTag("Obstacle"))
{
SpawnHitEffect(transform.position);
Destroy(gameObject);
}
}
private void ProcessHit(GameObject target, Vector3 hitPoint)
{
// Apply damage
Enemy enemy = target.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
Debug.Log($"[PROJECTILE] Hit {target.name} for {damage} damage");
}
}
private void SpawnHitEffect(Vector3 position)
{
if (hitEffectPrefab != null)
{
GameObject effect = Instantiate(hitEffectPrefab, position, Quaternion.identity);
Destroy(effect, 2f);
}
}
}
this my projetile controller
!code
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
A tool for sharing your source code with the world!
If it's a 2d rotation, I'd set euler angles with atan math
This code is only controlling the projecting, not instantiating it
Where are u instantiating it?
A tool for sharing your source code with the world!
I'm currently not on pc. But it seems you only need z rotation, x and y will make your projectiles rotate in a way where you will often not see them.
I might be wrong tho as I don't use quaternions often and they often caused issues for me in 2d
hmmm.. oke you know a better way ?
is this coming from java? c# has properties, you don't need all those public getter methods lol
(not an issue, just something you could utilize to make it more concise)
instead of a field and a method:
private float x;
public float GetX() => x; // shorthand for `{ return x; }`
```you could use a property:
```cs
public float x { get; private set; }
You take direction x and y and set your object's euler angles to new Vector3(0,0,Mathf.Atan2(y, x)* Mathf.Rad2Deg);
Also you don't need it on update, only rotate once on spawn
Oh fg
No need to do all the trig yourself
Did it help?
im tying it rn
If it doesn't work there are also these questions. #💻┃code-beginner message
can i send pic off my scene ?
sure
why is X your "forward" 🤔 aren't you doing 2d
that is definitely pointing in the wrong direction
(if you can't tell what's wrong, try changing to the 3d scene camera at the top of the scene window)
wrong quotes
Fixed it!
(also add cs)
Am on phone. All quotes are the same
they most definitely are not
Mostly
...yeah, no
Initially they seemed to look the same 🥲
a language for the codeblock would also be appreciated
```cs
// your code here, on a separate line from the fences
```
oh yeah, fair enough. you'll probably get used to it if you use them enough. ive found i use more muscle memory for getting different quotes rather than looking on mobile
is this right float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
proj.transform.rotation = Quaternion.Euler(0, 0, angle);
doesn't seem wrong, is this the code you were previously using?
(make sure to save first)
(also please format code properly as described here)
no its new code
perhaps try it before asking 😉
you can just do what Praetor suggest and do transform.right = myDir
but you gotta fix your orientation properly
kinda hard to explain
but basically i have a Ground Check for a rigidbody
isGrounded = Physics.CheckBox(groundCheck.position, checkBoxScale, boxOrientation, groundLayer);
i also use a RigidBody based character controller.. and i have root motion animations.
when i perform the "Roll" animation.. when just before it ends the animation the "isGrounded" CheckBox is getting collided with the ground mesh.. and for a 0.1 second it feels bad.. like a glitching.. or hitting the Air.. i'll try to send Gizmos as well...
the locomotion animation logic with groundcheck
//-- locomotion animator
if (isGrounded)
{
float targetSpeed01 = moveInput.magnitude; // from 0 to 1
animator.SetFloat("BlendSpeed", targetSpeed01, 0.1f, Time.deltaTime);
animator.speed = moveSpeed;
animator.SetBool("Falling", false);
}
else // play animation for the Falling and stop the movement.
{
rb.linearVelocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1f) * Time.deltaTime;
animator.SetFloat("BlendSpeed", 0, 0.1f, Time.deltaTime);
// animator.SetBool("Falling", true);
StartCoroutine(DelaytheFall(fallDelay));
}
// --- JUMP ---
if (jumpPressed && isGrounded)
{
animator.SetTrigger("Jump");
}
the one more interesting fact is that the Glitching effect stops if i play at 4k resolution... idk if this info is usefull...
can you help?
it just looks like the animation making go under the ground then the physics snaps it back up ?
or actually other way around
it floats for a bit then gets pushed down when gravity activates / rigidbody
yeah but i have constant gravity applied at the rigid body also when i jump off a block it still is making that animation linearly.. so root motion isn't applying gravity it seems...
why would it? root motion overrides the transform
i'll try to disable root motion as long as jumping is active
personally i just time it through code instead of relying on root motion when i got physics
yeah i thought about it but i wanted to add custom animations for it later... but i think i should , as you said, time it trough code later and keep the simple animation.. yeah probably will be less of a brainrot.

could I get some help with my code? I'm pretty new and as the code is written right now, it obviously changes the colour very fast at high framerates and very slowly at low framerates. Could I get a pointer as to how I could make it tied to a certain amount of time? Like, if I want B to go from 0 to 255 in 4 seconds, how could I do that?
using UnityEngine;
using UnityEngine.InputSystem;
using System.Collections;
using System.Collections.Generic;
public class Hunter : MonoBehaviour
{
public SpriteRenderer rend;
//for changing the renderer in unity
public float R, G, B;
public Color currentColor;
//for colors
void Update()
{
if (Human.blueDead == true && B < 255)
{
B++;
}
if (Human.greenDead == true && G < 255)
{
G++;
}
if (Human.redDead == true && R < 255)
{
R++;
}
currentColor = new Color(R/255, G/255, B/255);;
rend.color = currentColor;
}
}
you need Time.deltaTime
i figured, but I don't really know how to add it
i forgot about for loops but i dont know what a coroutine is
I think it has an example of this too
you could use a scale from 0 to 1 instead of counting up to 255
that way you can use fractions
basically you'd specify how much time it should take overall, and then you'd keep track of how much time has passed
yeah this was the fastest and easiest way I thought of, just to make sure it works first. But then i realized I have no clue how to actually do it properly
dividing the latter by the former, you'd get a value from 0 to 1
that's exactly what I'm looking for
for future ref myvalue += speed * Time.deltaTime //independent of framerate
right now the ++ is basically what's counting up, 1 each frame
but you'd want it to count up some amount each second instead
that's what deltaTime is, a conversion factor - it's seconds per frame
thanks
I'm not sure I fully understand yet but I'll try reading the coroutines page and test some stuff out. I'll return if I get stuck again. Thanks y'all <3
you don't really need coroutine, just putting it as an option as well
Update will be fine too
yeah I know but it seems like a tool that would be useful to learn for the future
oh fo sho
https://docs.unity3d.com/ScriptReference/Coroutine.html
this a bit more clear
personally i don't use WaitForSeconds but it is quick. I just use. DeltaTime there too with my own timer / while loop.
Update:
Fixed it trough adding the Delay for Actual jump.. and baked the Y position for the Root Motion...
[SerializeField] float jumpForce = 5f;
[SerializeField] float jumpDelay = 5f;
if (jumpPressed && isGrounded)
{
StartCoroutine(HandleJump(jumpDelay));
animator.SetTrigger("Jump");
}
IEnumerator HandleJump(float delay)
{
yield return new WaitForSeconds(delay);
rb.AddForce(Vector3.up * jumpForce * Time.fixedDeltaTime, ForceMode.Impulse);
}
thanks for your help nav

🫡
I don't think the deltaTime will be necessary there esp an impulse
AddForce already moves it on fixed physics tick*
if you're trying to sync up the actual force with an animation use an animation event rather than a specific delay so that you can sub in any animation with the event and have it correctly synced rather than needing to adjust the timing manually.
also yeah, don't use deltaTime with forces. you'll likely need to reduce the jumpForce in the inspector after removing that extra multiplication
oh and if you want consistent jump height it's usually best to also reset the vertical velocity to 0 right before adding the force
string chatName = allDataInMessage[4].Substring(1, splitPoint - 1);```
How do I change this so chatName equals the 2nd half of the message rather than the first
Substring(splitPoint + 1)
i feel like there's definitely a better way to do whatever you are doing here though
but splitting would probably be easier to work with
is the first character always a = here? (somewhat unrelated)
no actually "=" is in the middle of the two strings, this is older code im trying to change up to adhere to the array ive now set up
also, is the end not exclusive?
why is 1 there in IndexOf and the start of Substring then
yep that did it, thanks
would splitting a string rather than just working with a custom type that has the info already separated into relevant properties be easier though? because from what little they've shown, it seems like this is probably stuff sent over the network for a chat message and they can, and probably should, just use a custom type instead of packing it all into a single string and manually splitting it
ill be honest a friend went through it with me cuz im struggling to understand, and it worked fine until the string im parsing through got bigger, so this code is not relevant to what I'm doing now
oh it's a length. im too used to slicing
but your solution worked so thanks :)
struct {
string author
string message
oh that'd definitely be better, i wasn't thinking about changing the input
you mean this?
allDataInMessage = message.Split(new String[] { ";" }, StringSplitOptions.None);
for(int i = 0; i < allDataInMessage.Length; i++)
{
Debug.Log(allDataInMessage[i]);
}```
i mean, actually defining a type that you put your data into so that it isn't all in a single string
that's not what i was referring to either
Don't iterate a string if not neccessary
hell you can even put date, modified time whatever other types in it
i dont understand what your message means, the whole message arrives in a single string, how do i split it without splitting it?
you put it into your custom type at the sender, not at the receiver
Its not gonna be a single string... it will be its own type
then just deserialize it at the receiver back into that type
like ChatMessage chatMessage = new()
chatMessage.author = "username "
chatMessage.message = "whatever"
if you want it to be compatible with not just c# you can probably just make it into json easily
single string then splitting shit is absolute nightmare
if your message has symbols you defined as split string symbols you're gonna have a bad time and account for that
public struct ChatMessage
{
public string Name { get; private set; }
public string Message { get; private set; }
public DateTime Time { get; private set; }
//etc
public ChatMessage(string name, string message, DateTime time, etc)
{ //assign to properties }
}
void SendMessage(string message)
{
var chatMessage = new ChatMessage(name, message, DateTime.Now, etc);
//logic to actually serialize then send the message over the network
}
void ReceiveMessage(ChatMessage chatMessage)
{
//this is the end point that has already deserialized the data back into a ChatMessage
Debug.Log($"[{chatMessage.Time}] {chatMessage.Name}: {chatMessage.Message});
}
basically that, but obviously not the stripped down version that this is
and how do i grab the giant string of data coming in and parse it into these variables if not with a .Split?
where is the data coming from ? if its a json its easy to convert into object
you don't because you don't use a giant string of data in the first place. you use this ChatMessage struct and serialize that, then send the serialized data over the network, then at the receiver you deserialize it back into a ChatMessage. at no point do you construct a giant string of data that will need to be manually split
-# well, clearly not json with ; and =
yeah so they're probably writing the data in the first place, so don't write it as giant string lol
I meant if its needs to be a long string, json at least is formatted
im getitng the data from StreamReader using the twitch client GetStream
reading chat messages sent on Twitch
I only worked with discord, but pretty sure twitch also has some type of sdk or api you can get the message properly formatted
presumably it's sending json from its api so you would just create a type you can deserialize that json into
feels nice! finally works without major glitches. spent whole day .. LOL
https://dev.twitch.tv/docs/chat/send-receive-messages/
ya this does say they come in as JSON / and sent
i think im good guys, this is just a personal project anyways
nice!
just looked up the api, and yes. its endpoints all return json that just needs to be deserialized so all of this manual parsing of the messages is pointless and just serves to waste time and performance
im just a beginner man why you gotta be so mean
at no point was i being "mean" here, i am simply pointing out facts. it takes just a few minutes to look up how to deserialize json, and unity even has some built in tools that should be able to handle this easily
especially because you're new, its better to learn proper from the beginning and knowing the better options you have available to you especially with a type-safe language
splitting strings can be also very error prone
sure thing guys, ill talk to a coder friend of mine when theyre free about how to deserialize the message
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
though with stuff like Newtonsoft you don't need ALL the fields
but calling someone's honest effort a pointless waste of time and performance is mean, even if you don't think so or even meant it
if you cannot take constructive criticism, then perhaps don't ask for help online 🤷♂️
but manually parsing these strings does take more time than simply learning how to deserialize the data properly. it's also going to take more performance to do so because of the number of times you are querying these strings
how did you even get these strings into this format in the first place? because with the data being sent as json there shouldn't even be any = or ; to split on unless those are in the actual chat message (which means your split is breaking, hence the extra time to figure out how you can avoid wrongly splitting the string)
what do you mean by json, im getting this data as a string through the code.
reader = new StreamReader(twitchClient.GetStream()); + string message = reader.ReadLine();
is giving me the message as a string
ohh I was trying to figure out the same thing for a bit during the unity jam but the IK made it extra annoying 🥲
but yeah Animation event simplified things lol
with twitchClient = new TcpClient("irc.chat.twitch.tv", 6667); using other strings to get the twitch stream in question
writer.WriteLine("PASS " + password);
writer.WriteLine("NICK " + username);
writer.WriteLine("USER " + username + " 8 * :" + username);
writer.WriteLine("JOIN #" + channelName);
writer.WriteLine("CAP REQ :twitch.tv/tags");```
is there a reason to use TCP client instead of the API ?
every tutorial online ive seen does this okay, don't ask me
so you're not using the api of a very similar name then. you need to actually provide this info up front, you can't just expect us to intuit that you are doing things like this
i only asked how to split a string the other way around man...
you kept prying about it 😭
people often want to know more so they can give you the best solution to a problem, no reason to get defensive
because what you are attempting to do is incredibly fragile and will break
whoops someone's message contains a character you're splitting the string on, now your entire setup is broken!
https://xyproblem.info this page explains what's going on here pretty well
the X here being getting info over a network
the Y here being the condensed info string with manual parsing, when the better option would be proper serialization and deserialization (what nav/boxfriend are trying to explain)
you know what, fuck it, i cant change how you think.
anyways, thanks Chris ill check it out 👍
Hi! I need some help. Who can help me with my project? I have some problem with my navmesg in procedural maze
seems you tried moving agent without being near a valid navmesh
but i have navmesh
your navmesh agent is not near it / its not valid for it
without showing the setup you got goin its hard to offer any other suggestion
more than likely this might not even be a code question but a #🤖┃ai-navigation
But i think its code becouse we have procedural gen maze. In screenshot you can see room who build maze
I can send code if it can help
Its all codes for generation
yes but the issue is with you trying to navigate a navmesh agent while a navmesh isn't available
I dont understend how it work( enemy cant go to another blue place bcs have chasm
I dont know how to fix it
you need to learn more about how navmesh works
why are there gaps?
all ... i dont khow how it work in unity bs i work in un4
this is a code channel
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
love the dithering effect. 🔥
I’m adding an enemy to my game that i want to move using transform.translate since I don’t need it to have physics collusions. However, it does have a trigger collider attached to it so it can hit the player and deal damage. If I move it directly with transform translate, is this incompatible with the hitbox detection?
moved this from unity talk cause accidentally posted in wrong channel
its sketchy because colliders are still physics
hello guys i'd like to know how to make a good raycast that will shoot from the middle of the screen i have tried to shoot from the camera but its not really accurate :) In case you need it, here's my script. RaycastHit hit; Debug.DrawRay(transform.position, CameraDirection.transform.forward * 10, Color.red); if (Physics.Raycast(transform.position, CameraDirection.transform.forward, out hit,10))
so should i just make it kinematic and set velocity directly
translate can work with triggers but it has to "catch up" and can yield inaccurate results
you still need a rigidbody between the two
player has a rigidbody
should they both have a rigidbody?
u only need 1
ideally your origin would also be the camera's position, not this object's position, that way it does accurately shoot from the center of the screen in the direction the camera is pointing
kinematics by default dont have velocity (in 3d physx at least)
so as long as player has a rigidbody i can use transform translate on the enemy
oh whoops
check this chart
https://unity.huh.how/physics-messages/trigger-matrix-3d
ooh
so wait should i:
- not give the enemy a rigidbody and move it with transform translate
- give the enemy a kinematic rigidbody and move it with transform translate
- give the enemy a dynamic rigidbody and move it by setting velocity
cause it seems like all of those would work accroding to the chart
wait if the transform is the camera then it should work well no ?
if player has a rigidbody and collider, it should work
it would. but that's clearly not the case here. this component is attached to the player, not the camera, right? (hence why the ray originates at the center of the player and not the camera's position)
as in all of them should work?
so i should do the first one for simplicity?
depends what you need to do, generally a rigidbody per enemy can be taxing depending how many enemies you will have
uhm , i have attached the camera to the player , but the camera still move right ? i dont know if this is the good thing to do tho 😆
oh no i'v done transform.position
i think i might be dumb
if you want enemies to get hit with a trigger and do damage, then you need the trigger that hurts them at very least to have a rigidbody
ah wait looking at the chart closer the player hurtbox doesnt have a rigidbody
so ill give the enemy a kinematic rigidbody
unless its better to give the player hurtbox a kinematic rigidbody
okay. my fault , it works now thank you for your help :)
if you're dealing damage to player the player trigger is the only thing that needs rigidbody, the enemy that hits it can just have another trigger
ok so all my hurtboxes should have a rigidbody and all my hitboxes shouldnt?
does this create problems since the player already has a dynamic, is not trigger rigidbody for collisions with the ground?
player hits a trigger to hurt it , you dont need a rigidbody on the hurtzone
if player has rb
yes but the player has 2 diff colliders
one is a dynamic not trigger rigidbody and collider for where it can collide with the ground
iirc the rigidbody counts child colliders are part of rb but I could be wrong
As a rule of thumb any object that has a collider and is moving should:
- Have a Rigidbody (it can be kinematic)
- Should move via the Rigidbody (rb.MovePosition in FixedUpdate for kinematic)
got it
thanks
ive got a script that activates another gameobject after some time, how can make it so that the gameobject does something upon activating from code attached to it(the gameobject)?
put a component on it that has the OnEnable method
One option is to directly call a function to do the thing
myObject.SetActive(true);
myObject.GetComponent<MyScript>().DoSomething();```
another option is - as box said, use OnEnable
Hi, so im a bit stuck, my PointerEventData does never run for some reason, everything should be setup right so I dont really know what to do
my PointerEventData does never run
What does that mean?
PointerEventData is a class. Classes don't "run"
It means that this method wont run:
Ok you mean OnDrag won't run then
yeahh
Posting code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Wait does the name of the method do anything?
I don't really know how to answer that question
The name is required to implement the interface you should be implementing
You need to show the full script
Yeah, so here is the code for the InnerImage: https://paste.mod.gg/mjsgwepbbrrk/0
My setup (see image)
A tool for sharing your source code with the world!
Can you show your console window while the game is running?
(and preferably while or after you drag)?
Also show the inspector for the InnerImage object
Here if I click space for example
https://paste.mod.gg/mjsgwepbbrrk/0 This code doesn't look like it would compile to me
A tool for sharing your source code with the world!
Have you saved your code?
You have IPointerDownHandler but there's no OnPointerDown method implemented, that should be a compile error
Yeah it doesnt exist
What doesn't exist
Sounds like you haven't saved your code
I have 🙏
Why does it have a BoxCollider
UI should not have colliders
becouse I just tried in a hour to fix this thing with chatgpt
and he said I needed it
remove the collider
for some reason
Because you confused it with world space physics objects
you don't need that for UI
You also have an Event Trigger component that may be interfering
both are removed now
Can you show your canvas inspector too
yeah
hmm i do wonder if the mask is doing something here 🤔
If you put IPointerEnterHandler/IPointerDown on the script does that work?
Yeah im wonder where the logic is in this stuff
thats a very small image
Also yeah can you actually see this image?
this image?
the image of the innerimage
In game view when you're actually playing the game
💀
yeah but in the game itself
Also is this a first person game?
yes
yes
Pointer events with a locked/hidden cursor don't usually work
are you unlocking/showing the cursor when bringing up the map?
Yeah that'll be why. Search for "Unity eventsystem IPointer locked cursor"
what are you trying to do with this code then
mouse dragging doesn't make much sense to me with a hidden cursor
this:
I would just read the mouse delta input directly and move the map based on it.
this isn't pointer dragging behavior, since there's no pointer
Do you mean the innermap?
innerimage
Would it result in this then?
sure
honestly don't feel like I would use canvas/UI for this at all. I'd probably use a quad with a material and change the texture offset
but same difference
it's easier for me.
Try this:
make a new material.
Add your map image as the albedo image on the material
Add a basic quad to the scene
Put the material on it, you should see the map on the quad.
Then modify the offset in the material inspector
and see what happens
you should get the basic effect you want
it will require a little tweaking after that for scaling and stuff but should get you most of the way there
Then once you want to do it in code you use this on the material:
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Material-mainTextureOffset.html
Should the material be under the main camera then?
ooh
the quad is the thing that goes under the cam instead of Canvas
im dumb but where do you find albedo image in here?
Base Map
which section?
Albeido is the name for Standard materials
if you don't want the quad / map be affected by lighting you can also make it Unlit instead of Lit
NOOOO unity I hate you, why do you remove all my stuff when I pause the game after having it on 😭 😭 😭 😭
To be honest you'll probably want a (simple) custom shader for this to insert white pixels at the edges or something, but if you set the wrap mode on the imported image to "Clamp" you'll get a decent result to start with
what helps you recognize you're in playmode you can use play mode tinting in the preferences (if you mean the changes reverted from play to stopped)
not sure why its not default
can you show a quick video
Are you dragging the material onto the quad or the texture
ooh, wait I did drag it to the mesh collider
nvm
but should it be the mesh render?
yes
A renderer has a material.
The material has a texture.
The texture is your image file.
press the little > on the materials part
there's a place to put the material inside there
replace the default one with your custom mat
yoo this is cool stuff
you probably wont need a mesh collider for this
wait how?
cool
But as I want right now do I want one white image and then a inner image, how should I do that now?
like in this video
clone it maybe ?
or you could make the mesh have 2 materials but you probably would need to figure this one in blender
oh, so like two quads then?
could work, but remember you don't need mesh collider otherwise other objects that move like an enemy might bump into it
or even your char
btw, I cant really hardcode the map image, because the player will upload it
thats fine you can assign textures to materials at runtime
do keep in mind that this is a world object so if you run into an obstacle and your player collider not big enough it will phase into object
for that you can set this layer into its own thing then use a Renderer Feature that allows you to make this object appear over everything else so if you bump into a wall you don't have the map phase through it
I take that when it comes
I think
unity has one built in its pretty good
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@12.1/manual/renderer-features/renderer-feature-render-objects.html
but I still dont really understand how to do the backgrund image thing
did you try duplicating the two quads, one with whit bg and one with texture??
but why would I need to objects (two quads)?
that's what I was mentioned above with a custom shader
it would be a very simple custom shader
but for now I would just recommend setting your image to Clamp
you want two things
theres many ways of doing that
Im counfused should I make a shader or two quads or both?
one or the other
but the shader will be a simpler setup overall
and two quads would require a masking technique
what will that do=
have you tried changing the texture offset yet?
Did you see what happens?
yeah it dissperad
or wait
if the value is less then 1
it moves
But I want to be able to rotate the image
also zoom in / out
not just offset
is that what the shader is for?
yeah that's why you need a shader
you can probably look up a simple rotatable/offsettable shader
okey, I will do that tomorrow, but how do I detect mouse interactions in this cause?
its 1 node with ShaderGraph
depends which input system you're using
but that's an input handling question
since you're using the new input system you'd make an input action for the mouse input
and then read it
I google how to do that tomrrow ig
[SerializeField] private InputActionReference mouseAction; // default actionmap should already be there for mouse if input system is installed, drag the action "Look" here in inspector
Vector2 mouseInput;
void Update(){
mouseInput = mouseAction.action.ReadValue<Vector2>();
you've presumably already done it once to handle mouse looking around in first person view
I guess this maybe
that's the old input system
but - if you're using both, then yes
you can do that
Seems like your project is probably using both
old youtube tutorial lmao
the other one got genereted when I created the canvas
Thanks for the help god night
configure your IDE proper at some point, it will be handy for underlining errors / showing you the available methods, properties etc
Visual Studio Code guide
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
Is rider good?
I have the student package from jetbrains (which contains rider I think) because I’m using intellij for my Minecraft plugins
I don't use it but heard good things from it, if you have it for free with student pack go for it
idk if student license allows commercial projects, look into it (if you plan on making money from this game)
but also whats stopping you from just switching to a different editor pre release 🤔
I’m trying to use additive async multi scene loading using the built in save /load scene system but running into some issues .
Firstly , the scene transition worked fine when just using standard save / load new scenes but since trying to make it additive I run into alot of errors .
I just wanted to check it there were any key “ rules “ around using Save and Load scene in this way .
I believe my issues stem from duplicated cameras and event scripts but not 100% . Just wanted to see if there were any known Do’s and Dont’s - thanks for any help in advance !
pretty sure you have to make sure that each additive scene only has one active event/camera controller
i think
That’s sounds about right in regards to the errors I got
but im not too familliar with the workflow so i would stick around for someone else to give a better answer lol
Ha no problem thanks anyway though . I’m brand new to unity so it all helps !
Hey guys I wanted to ask
How would I go about connecting things (like a node system) in unity?
I would connect the ins and outs of gates like this to do some operation based on t he connected data
It's unclear to me if you're asking about:
- An abstract data structure
- a UI for representing such a structure
- and in-game system representing such a structure maybe with visible connections
like visual scripting or are you talking about implementing a system from a gameplay perspective
like - are you trying to make a boolean logic gate game, is that the question?
yeah basically
I just want to make a UI to represent the structure as you said, as I have made the class already, and use the UI to get the input (and current gate being used)
so pretty much just a boolean logic gate game
I wouldn't use UI, for one
a system from a gameplay perspective
So I guess my question is what part of this are you struggling with?
The visuals?
The logic?
the data structures?
what do you mean by logic?
logic - like... the actual code that evaluates the results (and maybe the intermediate results at each node)
No that I got hang of
I'm more struggling of getting the input from user if that makes sense?
Like I have the code and function ready, I just dont know how to use it when unity comes to play
to show these things in game
That's up to you, and is sort of a gameplay design decision.
You could have a node that just outpiuts a solid 1 or 0, and have the player place those in the game world
or just have them there automatically
and have the player place or connect other nodes
I could see this being done by allowing the player to:
- Place nodes
- connect existing nodes
- change the type of existing nodes
or all of the above
but that's a gameplay design decision
yes thats what I had in mind
I'm struggling with (connect existing nodes)
I'm confused by how to make that happen and how to get data from node connections
well presumably your nodes have some list of "input nodes"
that is true
when you make the connection, you add your node to the input node slot for the node you're feeding into
like a simple example:
class OrNode : AbstractNode {
AbstractNode[] inputNodes = new[2];
public void SetInput(int index, AbstractNode node) {
inputNodes[i] = node;
}
public override bool Evaluate() {
return inputNodes.Any(node => node.Evaluate());
}
}```
how to serialize/deserealize list of objects?
like this
{
"objectData": [
{
"id":1,
"name":"object 1"
},
{
"id":2,
"name":"object 2"
}
]
}
with JsonUtility is tricky but you can create two classes, one for the object and another for List wrapper
thats what i want
what do i write in my root obj
[System.Serializable]
public class MyObject{
public int id;
public string name;
}```
no
i know that
this is object code
now smth like
[System.Serializable]
public class Savefile{
public List<MyObject> objectData;
}``` i guess?
pretty much
you can use Newtonsoft and not deal with wrapper
whats newtonsoft
also i want to make my project as independent as possible
its actually called Json.Net but
anyway im comfortable with jsonutility
because im used to it and well...
i already have a project to copypaste savefile manager from
jsonutility is fine just annoying to work with especially with properties, dictionaries you have to always make wrappers
json.net gives more granular control
imagine what, i have to make my system with error from the past
2 jsons in one file
like it has 2 root entries
pretty smelly but yeah iirc json.net can handle that with ease
how can i switch?
yea when i received the tech docs i also almost falled from my chair :\
its like this
{
"somecrap":"fdihdffd"
}
{
"someothercrap":"bruh what"
}
thats why I said its pretty powerful tool but make sure to read the docs
heh
i remembered a joke
a monkey is calling the devs of a lib instead of reading the docs
dont be dumb as monkey
continuation: monkey is actually smart because nobody wrote the docs
but there are some tools that dont need a doc
“Why do you keep calling us?”
And the monkey just shrugs:
“Why do you keep shipping undocumented features?”
like this piece of code (one of the worst type of protection for savefile in the game):
static public string ProcessSavefile(string input)
{
string output = "";
for (int i = 0; i < input.Length; i++) {
output = output + (char)(input[i] ^ key);
}
return output;
}
yea its basic XOR key prot
ohh protection ?
kinda
I just create a hashing system xD
but its really dumb to encrypt json savefile with xor
if it don't match the hash, sorry you fucked up your savefile.. I dont accept it
scince any json must begin with {
if its json you cant protect it
from tampering no, but you can verify that it was fucked with through hashing
also without obfuscation il2cpp dumper + dnspy + ida goes skidddd
i create a secret copy of the original save file, if you mess with the one from the common user folder. I just restore it from the "secret copy"
LMAO
in most cases they can find where you save that too though
so if you brick your save, sucks for you
lets be real: you can just use handle list
btw afaik minecraft does same thing with level.dat (yes worlds are called levels)
hm interesting.. I never checked their code
not code
ofc you can always make your game "always online" and use servers, thats pretty much tamper proof
but you can then make a hack by making game offine
there is no unhackable system
but some systems are taking longer to hack
its a game of cat and mouse
yes thats the point, you have to make it as tedious as possible.. indeed nothing is truly hacker proof. thats why these AAA studios spent tons of money on
Why try and safeguard the save file in the first place
remember Fallout 76 and all that bullshit with the Devrooms
checking the hash of a local save wow 😆
heh make these fuckers regret messing with their file!
If its a single player game honestly dont bother making it tamper proof
People will appreciate the extra freedom ngl
that was their fault and things are alot better now. Most legacy weapons are gone now
hard lessons learned Im sure
Yea people will either find a way to do it properly, mod the game or just hate you
i would hope it was their fault would be abit worrying otherwise 😅
ya true as well.. depends how devious you're feeling 😈
it can mess with the pacing of your game though in some cases
unity = easy to hack, godot = easier to hack, clickteam fusion = overpriced and overrated bs (easiest to hack) ue = hard to hack custom game engine = almost impossible to hack without spending your whole life
clickteam fusion holy shit
native language without reflection moment
thats what i meant
i know!
like if you write your game from scratch in C++ and asm and then vmprotect it, it will be more practical to drop it
Almost impossible is coward talk people are starting to decomp gamecube and wii games 😛
there will always be psychos
get the package lol
use JsonConvert.SerializeObject instead of JsonUtility.ToJson
etc
so i can just use my jsonutility typedefs for json.net?
yes
only changes which methods you use, you can keep everything else the same. As mentioned you also wont need most wrapper bs you need for JsonUtility
ok
the only thing you need to be careful with is Vector2/3 struct as it causes weird error
cause it creates a Self-referencing loop error
easy fix tho
You can use float3 from unity mathmatics as an alternative
or make your own struct too
they have implicit conversions to Vector types
im kinda new to serializing, how to represent this:
{
"playerData":{
"x":21,
"y":56,
"z":53,
"ry":82,
"rx":24
}
}
make class
Convert any JSON object to C# classes online. Json2CSharp is a free toolkit that will help you generate C# classes on the fly.
how can i make an object in json that can be dynamic?
i need to save object data, but diffirent types of objects have diffirent properties
like polymorphism ?
yea kinda
or maybe use a dictionary
Depends if you do want to develop these constructors, but I would just keep everything typed correctly
like one object (a gun for example) has properties like ammo left in clip, but a basket can have a list of items in it
i will need to expand it in the future
Really just make as many structs/classes as you need
no
not what i need
{
"Id":"Gun",
"id":71929404,
"pos":{
"x":-7.31680632,
"y":-1.62211561,
"z":6.726395
},
"rot":{
"x":-0.00672015827,
"y":-0.9603869,
"z":-4.31004446E-05,
"w":-0.278589338
},
"data":{
"ammo":12
}
},
{
"Id":"Basket",
"id":-133609697,
"pos":{
"x":-5.947119,
"y":-1.24142826,
"z":7.639765
},
"rot":{
"x":-0.000139048585,
"y":0.999806643,
"z":-0.0003319612,
"w":0.0196609721
},
"data":{
"items": [
{
"Id":"Gun",
"data":{
"ammo":12
}
}
]
}
}
thats what i meant
gun has ammo in its properties, and basket has another gun inside with 12 ammo
yeah what i meant
i think dictionary could work here
but can i make Dictionary<string, Object>?
you can make Dictionary<string, object> sure
and it will parse correctly?
thats pretty much what Unity uses for Unity cloud for PlayerData
newtonsoft yeah but JsonUtility follows similar editor serialization rules
sum like this might be a lil cleaner though
public abstract class SaveObject {
public string id;
}
//Gun
public class GunSave : SaveObject{
public int ammoLeft;
public int clipSize;
}
//etc.```
```cs
var objects = new List<SaveObject>();
objects.Add(new GunSave { id = "gun1", ammoLeft = 6, clipSize = 12 });
objects.Add(new BasketSave { id = "basket1", items = new List<string>{"apple","knife"} });
string json = JsonConvert.SerializeObject(
objects,
new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
}
);```
so if i have
{
"someShit": someOtherShit
}
it will parse down to
{
"someShit": {
"someOtherShitProperty":"xD"
}
}
```?
i made this scene to learn navmeshes, just two capsules, setting their destination to the target position it works fine, but am i getting frame drops and why does this scene have 8k tris
where is the toothbrush
don't recalc every frame
but if be serious mark all immovable objects as static
also #🤖┃ai-navigation (?)
it will save some drawcalls
im not having issues with the ai, its more of a optimisation issue
are you sure thats cause fo slow down ? Check the Profiler
i see
can't say about the 8k tris (not a problem really) but turn on wireframe
doesnt look like much going on visually to be slowing down
unless for some reason you really are building navmesh every frame, that'd be insane
Profiler will pinpoint the cause tho
i know but this doesnt look like 8k tris 😅
capsules a little dense there
hey they are trying their best
lel, actually yeah unity capsules are pretty high poly
still better than this
this is my first time using the profiler, i dont feel like the graph dancing like that is normal in a game with so little going on visually
switch it to hierarchy mode and sort by ms
Deep Profiling also will show any code/methods as well
how do i do that
i figured it out
whats semaphore wait for signal
Cpu thread waiting for another GPU/CPU thread iirc
so that jump is normal
are those the only processes showing ?
yeah
weird normally is shows if its playerloop or editorloop
oh and btw found this .. so I was almost correct lol
https://discussions.unity.com/t/semaphore-waitforsignal-causing-performance-issues/775762
so yeah its a symptom but not the cause
random question
what unity version do you use
6.0.33f
knew it
these issues started when i upgraded to 6.2
i never opened a profiler cuz i never found the need to
could be , idk these "recommended" versions are pretty buggy
they're not final anyway
when 6.3 drops. 6.2 is already considered out of support
yeah im installing 6.0 back
LTS are usually more stable
Hey! We have a small minigame in our game where people have to click rather quick. We do play a hit sound. However we have the issue that sounds are quiet delayed after some time. In code I already added:
- Instead of playing each per OneShot() over one audio source, i added a pool of audio sources and play the events over them (apparently thats better? but doesnt fix the issue)
- changes audio to preload and PCM to maybe improve load time cuz i thought its bcs of that
- added a small delay to play the sound
but doesnt matter what i do, it always starts lagging out after 10-15 clicks... not sure what else i could do here? i mean ego shooters play multiple sounds per second with weapons, i cant even get 10 to play in 2-3 😄
is this in a new project? have you tinker with any quality setting cause default in a default urp 3d project it already set to high quality
isnt there currently no lts versions due to the security exploit?
scratch that
my unity hub has not been updated
now there is a version without the security alert as well.
just update to a patched version
why even bother
if you are making a singleplayer game that dont pull anything you can just ignore it
You should turn on deep profiling and see what shows up. That is definitely not the cause of your lag.
eh I just update the UnityEngine.dll binary
no reason to update all my projects to a new unity version if I can just patch the binary
im making a multiplayer game with lots of user generated content. That exploit exists only for games such as my own.
ive been on 6.0.2 but when I updated there wasn't any LTS versions showing. Unity hub needed an update is all.
updating all my projects when I know im on a stable version for me, I have no desire to update it any time soon
then ok
but in my case, where i make games that only pull data that is being stored locally by the game itself it doesnt bother me
as mentioned if need be, you can use whatever version is working for you then just use the patcher tool 🤷♂️
updating 30+ projects for me just to use a patched version of unity that may introduce possible bugs I never seen is nonsense when a binary patcher exists
you're actively maintaining 30 different unity projects rn?
ya bro lol
thats crazy
i could never be bothered to keep up with that many
most of my code is unity packages instead for that reason
doesn't help when you have adhd
a lot are collabs too, or client projects. I'm still trying to put something of my own on steam tho but that gets delayed by paid projects 😮💨
:\
(projects not editor)
not counting the ones on github that are not on disk 😅
my
ball
(player) keeps bypassing the wall
they all have rigid bodys so whats wrong??
Colliders are needed for collisions
oh
They also need to be moving via the Rigidbody
atp its time for a dedicated m2 drive
is transform.position teleporting
or is it moving
thats probably why its going inside of it
its teleporting
so its ignoring the collision
is the ball a rigidbody?
if it is a rigibody
move it using using velocity or using forces
you can either add force or set the linear velocity. Read the docs, follow tutorials/examples, and experiment so you'll learn how to use it
setting the velocity can function the same as using addForce
I'm trying to make a custom Playable for Rigidbody movement. It's my first time extending the Playables API.
I thought I could just give every PlayableAsset a reference to a Mover and a position, and then when the PlayableAsset starts playing I make sure the Mover gets there in duration time. However, as I see it, there isn't really a method that gets called when a PlayableAsset starts playing? Both of my PlayableAssets CreateGraph() methods are fired when the PlayableBehaviour is loaded in, and not when the PlayableAsset itself starts playing
I think you mean AddForce
But you can use AddForce or set the velocity directly, either is fine
https://pastecode.io/s/8kievjr7
https://pastecode.io/s/fh5afhsq
I. DO. NOT. UNDERSTAND.
How the fuck you are supposed to link two scripts.
No matter how hard I try, I always get NullReferenceException, and when I eventually find out what I had to do, I never really understand it.
Like seriously, look at the picture! How is it possible that it's reading the variable right, while also being a NullReferenceException at the same time 😭
How in the actual *@!$ can these two both happen in the same script?!
have you considered there could be two copies of this script ?
No, I suppose not
type t:PlayerHealth in the hierarchy searchbar
oh my god you were right 😭
Welp
Yeah I suppose that would be the only concievable explaination
I still really don't understand if there's a best practice when linking scripts
looks fine to me
private PlayerSpawnManager spawnManager;
[SerializeField] private FirstPersonController fpController;
Like in my very script
I have to do two different types of methods to link scripts
But like
Why?!
wdym two methods
One uses spawnManager = PlayerSpawnManager.Instance;
The other uses fpController = GetComponent<FirstPersonController>();
GetComponent isn't necessary especially if its on the same gameobject , stick with [SerializeField] private and link through inspector
only times you can't do that is linking prefab/or spawned objects fields to scene components, usually passing it through simple DI or maybe using singleton like you have on the first line there
singleton makes more sense for things like a spawn manager or whatever managers and you only need 1
Oh yeah, you're correct
so I can use .Instance if the thing is actually in the scene?
.Instance is just a static field you have created to assign it a specific Instance
assuming you assigned it in awake or whatever
you don't always want to make everything a singleton and use Instance
Gotcha
GetComponent or my preferable TryGetComponent is pretty handy when doing some sort of runtime Get like a raycast hitting a collider and you want to check if it has the type you want
Is there actually a place where I can read all of the ways people use to link scripts, lol
🤔 Unity, Huh, How?
Choose the best way to reference other variables.
That's the same method, setting a variable with =. Both PlayerSpawnManager.Instance and GetComponent<FirstPersonController>() are values that hold a reference to an object, so you can set your variable to those.
You can set a reference either in the inspector, or with =
if im saving nested JSON parameter as object, can i just do serializer.Deserealize()?
professor seems to not want to listen to me for help so i came all the way to the unity discord server
is there a way to call a variable in a game manager through a string? i want this script to be able to be used with various doors
like a dictionary<string, your var thing>? but i think the door should know what key can be used on or key know doors can be used on instead of the game manager knowing the doors and keys
if the class has the json fields i dont see why not
It's unclear how this code or what you're trying to do would benefit from what you asked about
But basically, you're barking up the wrong tree most likely
probably
You can do what you want without the need for that
changed to a switch case and i can do that
i will need to learn this properly eventually but i think this'll suffice for tracking wich keys i collected with one single script
Is there a channel for multiplayer related stuff?
There's a #1390346492019212368 channel
@wintry quarry do you know any solution for this.
if i have a sprite image is it possible to animate without using animation feature
like the hand movement
tweener is that free asset
Tweener is something that does tweening. There are free tweeners yes
what can i use in universal 2D to fadeIn/Out a sprite based on a collision?
alpha on the sprite?
alpha on the material?
how can i call the alpha of the sprite in C#?
sorry if it's a dumb question i'm new to unity
i'm trying to have a sprite with a 2D box collider have a event when my player enter in his box collider but it doesn't work , what am i doing wrong?
add a log and see what it collide with or is it trigger
Sprite does not have neither color nor alpha (well the texture has per pixel) but the sprite renderer does: https://docs.unity3d.com/6000.2/Documentation/ScriptReference/SpriteRenderer-color.html
How can i add a log?
does the object that the script is on have a trigger collider?
at least 1 one object need rigidbody 2d
it doesn't seem like the collision trigger itself works , i have my player with a rigidbody 2D and the sprite has a box collider Is Trigger so i don't know what i'm missing , would it be the scripting?
ok
but how can i make "polymorphism"?
basically diffirent objects have diffirent properties
and some have properties like objects inside of a container
ngl i dont understand
you serialize the child and deserialize as parent?
Are both the rigidbody and collider 2D, or did you mix 3D somewhere?
they are both 2D
in same layer? when you remove the trigger does the 2 collide
What method are you using for the collision check?
OnTriggerEnter/Exit2D
Do you have a log to check if anything collided?
i don't understand how logs works
Also, does the other objects have a collider?
the player has a rigidbody2D and the sprite has a box collider 2D
Just lookup how to use Debug.Log. It's practically vital, as you'll use it to check and debug everything you do . . .
i'm stupid
Okay, but does the player have a collider?
i just added a box collider to player and now it works
the facepalm is real , tkx for the help
You can't tell if it collides without a collider. That's its boundary box . . .
my enum method output becomes integer (enum index), even though i didnt cast it to int. this causes my if statement always false when comparing 2 enum
i used that same method to property return value and it worked just as I expected, so the method is fine.
public void CollectFloorItem(GameObject item)
{
Location location = GetLocation(item.transform.position);
for (int i = 0; i < areaScripts.Count; i++)
{
if (location==areaScripts[i].location)
{
//code never get through
item.transform.parent = areaScripts[i].transform;
}
}
}
its just a method to make the hierarcy clean
if it same enum it would return same int too so it seem like the 2 doesnt equal
Change it to this and show the console output:
public void CollectFloorItem(GameObject item)
{
Location location = GetLocation(item.transform.position);
Debug.Log("Location: " + location);
for (int i = 0; i < areaScripts.Count; i++)
{
Debug.Log($"{i}: Comparing {location} and {areaScripts[i].location}");
if (location==areaScripts[i].location)
{
Debug.Log("They are the same!");
item.transform.parent = areaScripts[i].transform;
}
}
}
i have only set 1 area, repairshop is ites 11th element, and unidentified is 1st element
public Location GetLocation(Vector3 position)
{
if (areas.Length <= 0)
{
Debug.Log("No area registered");
return Location.Unidentified;
}
for (int i = 0; i < areas.Length; i++)
{
if (areas[i].bottomLeftBorder.position.x < position.x && position.x < areas[i].topRightBorder.position.x &&
areas[i].bottomLeftBorder.position.y < position.y && position.y < areas[i].topRightBorder.position.y)
{
return areas[i].locationName;
}
}
return Location.Unidentified;
}
```this is getlocation
i set border gameobject on bottom left and top right (2D game), if the position is in between then its in the area
Areas is an array of struct, 2 border gameobject
What are the types of areas.locationName and areaScripts.location?
Add a log before you return the location name . . .
Debug.Log($"Location: <color=cyan>{areas[i].locationName}</color>");```
Can you show us your enum file?
!vs
Visual Studio guide
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
hm, that looks configured?
the one worked (OuterInn) is used in my npc thats spawning public AreaManager.Location CharacterLocation { get => AreaManager.Instance.GetLocation(transform.position); }
btw i also tried to cast both if ((int)location==(int)areaScripts[i].location), it doesnt go through
hi, is it safe to delete .meta file ?
how can I clear it then? as it is placed in the main folder but if we move the script, it is in the still in the same folder
it'll get regenerated as well - probably with different info that breaks links
oh but if we don't have link?
Unity cleans up the meta files itself
once assets get refreshed it'll be moved too
or you can move it yourself
oh?
i am blocked on this, is it normal?
i don't know when I was texting there it got this , but well it is over haha
you mean this?
depends on if you have auto asset refreshed enabled (which it is, by default)
if it's enabled, it'll refresh (& recompile) when you refocus unity
if not, it'll refresh when you refresh manually with ctrl+R, or also upon play mode iirc?
not sure on that latter part actually, i'll have to check
it deosn't work rip even when I press refresh
seems like no on that last point
https://docs.unity3d.com/6000.2/Documentation/Manual/AssetDatabaseRefreshing.html
what doesn't work?
meta fils still there
those are all supposed to be there
refresh of what?
also this is definitely not a code issue
those are the meta files for the folders
every non-.meta file and folder has a corresponding .meta file
yeah i know it but how can I make them move with the corresponding files ?
they are where they're supposed to be.
anyone use linux mint with unity/visual studio code? i'm having trouble getting vscode to connect to unity as it says something like wrong slnx because dotnet only shows version 8 while wanting 9 and i've tried installing version 9 and 10 using a script from microsoft via the terminal but vscode still says i only have version 8 of dotnet installed, it was working fine last week. sorry if this isn't the right place to ask but idk where to
have you tried with the .NET install tool
also, just to make sure we're on the same page - vs and vscode are separate products, i saw you using the vs configuration command earlier
No I'm not into Linux I haven't had the time to learn that. I like moicrosofts operating system better
-# you can just.. not answer if you don't have any useful answer
i get 'ms-dotnettools.csharp: Trying to install .NET 9.0.11~x64~aspnetcore but it already exists. No downloads or changes were made.' and 'visualstudiotoolsforunity.vstuc: Trying to install .NET 9.0.11~x64 but it already exists. No downloads or changes were made.' on start up in vscode
Hello everyone, I have a question about the proper logic for my code in general
Let's say I have a player character in the scene that collects coin to gain money, is it better that the main code to collect the coin value is located in the player or in the coin ? Which one should collect the colliding data about the other ?
it's up to your design, really. either could work, but ideally it'd be consistent across different objects
i made the switch to linux last year which windows was easier but annoying. linux has only been troublesome when i update stuff, i should turn off checking for updates when things are running smoothly
consolodating all the logic in the player would probably be the easier option
but vscode still says i only have version 8 of dotnet installed
could you elaborate on what exactly is stating this?
Ok I will try this, thank you !
i start up unity, double click a script to bring it up in vscode, it looks right but then shows an error in the bottom right and all the code loses half the colors with no autocompletion. in the output i get 2 messages of trying to install .net 9.0 but already exists
thats the error i get in the bottom right
it seems to be a recent error cause i only found 1 report of it online and a response within the last day
hmm the former error was about 9.0.11?
perhaps try uninstalling and reinstalling .NET
(note that nothing about that is saying you have .NET 8, you just don't have .NET 9.0.200 or above, apparently)
from the terminal i try 'dotnet --version' or 'dotnet --list-sdks' and says i have 8.0.121
are you using .NET for anything else?
even though i ran some script from microsoft to install 10 and 9
if not perhaps just uninstall everything and try installing again, with the .NET install tool in vscode specifically
this is the .NET SDK, specifically
used for developing stuff, not for running stuff
so, do you have any other (non-unity) projects using C# or other .NET languages?
(that would maybe need different .NET versions)
nah, i don't do much scripting outside of gamedev
so i'll try uninstalling stuff and try again. worse case scenario i just wait for a patch, i think
perhaps try this then yeah
and specifically don't use external installations
(not that that's bad, but using the .NET install tool has worked consistently, and there seems to be several things that can go wrong with external tools making them not link to vscode or something)
i have found the cause, me commenting an element out messes with my stuff in the inspector, causing the border to have unassigned Location field.
someone said along the lines "then that means it returns null" before editing it out. i thought my enum cant be null and it will assign Unidentified as default... 11 is the unassigned enum
enums can't be null, yeah
definitely weird. i just ran a quick test and only received the 'correct' enum names when returning and comparing them . . .
commenting out the enum element makes all the values shift
unity serializes enum values based on their backing integral value
basically, enums are just integers with names
oh, you mean, the comment in the enum declaration, right?
What you can have is an enum value that doesn't have a name. For example if you have:
enum MyEnum { A, B, C, D}``` and then you select D in the inspector, and then you edit the code to be:
```cs
enum MyEnum {
A,
B,
C,
//D
}``` then you will have an unlabled value in the inspector
or even if you did:
enum MyEnum {
A,
// B,
C,
D
}```
because the values will shift yeah
before, you had:
0: Unidentified
1: OuterInn
...
4: OuterCastle
5: InnerCastle
6: MeatShop
...
11: RepairShop
```after removing one of the elements,
0: Unidentified
1: OuterInn
...
4: OuterCastle
5: MeatShop
...
10: RepairShop
you generally don't want to be shifting enum members around, unless you specify a value for the members
If you plan to shift/insert them you should give them explicit values and don't ever change them
enum MyEnum {
A = 0,
B = 1,
// C = 2,
D = 3,
E = 4
}```
C# lets you do this
to answer this,
enum method output becomes integer (enum index), even though i didnt cast it to int.
they're already ints, they just have names on top of the integer value
Then to insert one:cs enum MyEnum { A = 0, B = 1, F = 5, // C = 2, D = 3, E = 4 }
How does allowSceneActivation work?
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/AsyncOperation-allowSceneActivation.html
What does 'Unity stops progress at 0.9' mean?
does that mean everything has been loaded, and the scene just hasn't activated yet?
what happens in the remaining 10% ?
can that cause performance issues?
i fixed it by downloading the 9.0 binary files from microsoft and placed them in the folder where dotnet sdk is suppose to be, /usr/lib/dotnet. which i found the 8.0sdk still after i ran apt remove on the dotnet-sdk-8.0. i didn't use the install tool as it kept saying i had 9 installed but, god help me, i have no idea where. dotnet --version now says 9.0.307 aswell
did you try uninstalling via the .net install tool from vscode
it probably keeps its own stuff
well if it breaks again, maybe try the instructions i gave
i didn't try that, i went through apt remove to uninstall which .net install tool probably wouldve done it cleaner
cause i still see 8.0 files lol


