#archived-code-general
1 messages Β· Page 271 of 1
I'm guessing you have a problem somewhere else. Maybe your ground check is wrong. Maybe vel is already compensated partially for your orientation and now you're double-correcting it here
I can't pinpoint the problem but I assume it has to do with verticalMove + groundedness
Yes.
if vel has already been rotated, rotating it again will give you a vector that points partially into the floor
Could it be me using transform.TransformDirection for the velocity?
If your player is rotated to (at least partially) match the slope, then yes, that's your problem
in that case, you'd need to use Quaternion.FromToRotation(transform.up, slopeHit.normal)
rather than rotating from world +Y
you can use Debug.DrawRay to visualize what's going on here
The players x rotation doesnt change
You mean X rotation
oh, one important thing...
Y rotation is side to side
you should rotate the desired move vector, not the player's actual velocity
You're rotating your actual velocity
so if you're already moving down the slope, this tries to rotate your velocity vector 45 degrees into the ground
which slows you down significantly
Good catch
I've implemented this exact thing more than a few times π
yeah sorry
Same, but it slipped past me
You mean do this?
Correct.
instead of this?
You want to adjust the intended movement
imagine you're already sliding down a slope
and you aren't trying to move
you shouldn't mess with the player's velocity at all
Currently I have this section to calculate acceleration, should I convert this into a vector three and rotate that then apply velocity? Because right now this is happening: https://streamable.com/555ffo
The short arrow is the player's velocity. The long arrow is the velocity after running it through SlopeVelocityChange
calculate the desired velocity, adjust it to fit the slope, and then do acceleration
That is what I am currently doing, and the thing in the video I just sent is the result.
Show me your new code.
Here is my whole script rn: https://hastebin.com/share/usekocugez.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
verticalMove needs to come out desiredVelocity.
that's not part of your actual move input
Break your original velocity into two pieces:
- the part that's aligned with the plane of the slope
- the part that's aligned with the normal of the slope
Use Vector3.MoveTowards to move the first part towards the desired velocity (which is constructed only from your move input).
Put the two pieces back together.
You'll need to know the slope normal to do that
Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeNormal);
Vector3 normalVelocity = Vector3.Project(velocity, slopeNormal);
planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);
velocity = planeVelocity + normalVelocity;
This gets around a major problem with the code:
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.y = verticalMove;
velocity.z = Mathf.MoveTowards(velocity.z, desiredVelocity.z, maxSpeedChange);
This doesn't let you accelerate in the world Y axis
which means you're accelerating slower on slopes
but didnt you say not to rotate the velocity?
This doesn't rotate the velocity vector.
Is that supposed to go in the SlopeVelocityChange?
I left out the part where you calculate and correct desiredVelocity
Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
desiredVelocity = SlopeVelocityChange(desiredVelocity);
But you need to know slopeNormal to do this correctly, so you'll need to grab that
I have it, from the raycast.
The player just went up a ramp super quick and back down super slow?
Here's what I got:
void PlayerMove()
{
Vector2 moveValue = move.ReadValue<Vector2>();
Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
desiredVelocity = SlopeVelocityChange(desiredVelocity);
Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeHit.normal);
Vector3 normalVelocity = Vector3.Project(velocity, slopeHit.normal);
planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);
velocity = planeVelocity + normalVelocity;
Debug.Log(desiredVelocity);
controller.Move(velocity * Time.deltaTime);
}```
doesn't your SlopeVelocityChange method check the sign of y?
if (adjustVel.y < 0)
{
return adjustVel;
}
yeah
so it's going to behave differently going up and down slopes
ah, and one other thing
Okay, well that fixed that problem, but now there is another. There is no gravity, I am just sticking to the ground.
Here is video: https://streamable.com/5sniy3
verticalMove isn't being included
Just add gravity at the end. You don't really want to keep track of the vertical move separately
since your movement can now go in the +Y/-Y direction
A separate verticalMove made sense when your movement was strictly in the XZ plane
You will probably want to use controller.velocity to figure out how fast you actually moved
Alternatively, you can set normalVelocity to zero if it's pointing into the ground and you're grounded
That's a good fit for how verticalMove used to work
so verticalMove (which could only be in the Y direction) is replaced by normalVelocity (which can point in any direction)
on flat ground, they're exactly equivalent
Give that a try.
The big idea is to get rid of "special directions" -- there shouldn't be an axis that behaves differently than the others
Like this?
I'd just write velocity += gravityVector * gravityMultiplier * Time.deltaTime;
gravityVector would be 9.81f * Vector3.down by default
And I do that before or after saying velocity = planeVelocity + normalVelocity;?
I guess I'd do it before splitting, but that's going to be a very slight change
Its currently applying the gravity along the slope or something, because I walked on the slope and flew super fast off of it.
Here is what I got:
void PlayerMove()
{
Vector2 moveValue = move.ReadValue<Vector2>();
Vector3 desiredVelocity = transform.TransformDirection(moveValue.x, 0, moveValue.y) * speed;
desiredVelocity = SlopeVelocityChange(desiredVelocity);
velocity += gravityVector * gravityMultiplier * Time.deltaTime;
Vector3 planeVelocity = Vector3.ProjectOnPlane(velocity, slopeHit.normal);
Vector3 normalVelocity = Vector3.Project(velocity, slopeHit.normal);
planeVelocity = Vector3.MoveTowards(planeVelocity, desiredVelocity, acceleration * Time.deltaTime);
velocity = planeVelocity + normalVelocity;
controller.Move(velocity * Time.deltaTime);
}```
hm, yeah, this doesn't have any friction
so gravity will send you careening off
See how it feels if you dramatically increase your acceleration. You should stop slipping off the slope
Yeah, its sending me off of the slope like a damn catapult rn, lol.
I step on the slope and slide up, but slower
Here is a video of it: https://streamable.com/3x095g
private IEnumerator TypeCoroutine(Fox talkingTo)
{
_dialogueText.text = fullText;
_dialogueText.maxVisibleCharacters = 0;
while (characterIndex < fullText.Length)
{
if (fullText[characterIndex] == '[')
{
int endTokenIndex = fullText.IndexOf(']');
string token = fullText.Substring(characterIndex + 1, endTokenIndex - characterIndex - 1);
Debug.Log("idx1: " + characterIndex + " token: " + token + " idx: " + endTokenIndex);
fullText = fullText.Remove(characterIndex, token.Length);
characterIndex = endTokenIndex + 1;
} else {
_dialogueText.maxVisibleCharacters = characterIndex + 1;
characterIndex++;
yield return wait;
}
}
wait = new WaitForSecondsRealtime(0.05f);
}```
im trying to parse dialogue text and remove emotion prompts like [happy], [sad] etc
but for somereason Remove is reversed and the starting index is the end of the string and the characters to remove go backwards ?
like if im not mistaken Remove's first argument is the starting index then the second argument is the characters to remove after that
charaterIndex is 0 and token length is 9, but the beginning string isn't removed at all, a text like "[happy]Hello! how are you?" becomes "[happy]Hello! how"
- given start index s_idx and end index e_idx
the length is e_idx-s_idx+1, then remove from s_idx with length e_idx-s_idx+1, no need to create substring - just move the pointer to index of ] +1
Isn't the issue before it even gets to remove? You make substrings based on ]
Did you try stepping through the code with a debugger?
wait, isnt the tmp text pointing to different string instance?
Why would it. ? doesnβt substring just take a piece from an existing string to a new variable based on index
Token is needed, since Iβm needing to get the emotion name between the [ and ] im not done with this code but I want to get this working before I continue
Oh and characterindex does become ] + 1
TMP.text=a_str;//here a_str contains emtional prompts
a_str=a_str.SomeChanges();//.SomeChanges() returns new string, TMP.text still pointing to old a_str
oh my god im so dumb. that was my issue
Hello so for my game I gave the player some health and when a specific animation plays the player takes damage but they are immediately dying π¦ idk why https://hatebin.com/mmwsqomihu
because you are substracting 50 health every frame your current animation is "Punch"
learn animation events
I tried but when i looked it up nothing came up
What keywords did you try searching with?
any ideas why in webgl scenes transitions may not working( I appears in main menu, then push the play button and nothing happening(in unity editor everything ok))?
make a debug build and upload it and debug
good idea
Well I made one of the animation events however it is saying it does not have a function name even though i set the method
What are the best practices in terms of refreshing nested Layout Groups?
how to handle UI state and its logic properly in unity? I know about MV_ family patterns, but its very sloppy to implement in the engine (at least for me)
I know it's more architectural question and I can do whatever works for me, but I just want to make "more clean" code, so I ended up doing UI manager that holds an internal event bus with all events and I just subscribe and fire these events by this manager interface
but I think there are more and more better ways of doing it, because all of my classes that interact with UI depend on this manager and its event bus
and it's very dirty and clunky to put this subscription and unsubscription all over the place in init logic of my scripts
maybe there are some resources or tutorials on this topic that you guys can share?
preferably for unit testing capabilities of UI classes
Hey guys, I am far into multiplayer fps game development with Unity. I have been lately debugging my lag compensation code and it looks like one box collider is offseted little bit on server in comparison to client. (or my box collider drawing code does not work)
I am drawing using object's (which got the collider) position, rotation, lossyScale, and also box collider size + center. It also seems like lossyScale is different by about 0.001 even though it should be (100, 100, 100) on both.
My question is: how can I 100% accurately log a box collider into console? Do I just need box collider's center & size, and then the object's world to local matrix, instead of using lossyScale etc?
#854851968446365696 #πβcode-of-conduct no crossposting
why does it sound like that?
how can we know?
We need a bit more info on that
Soundfile, code, settings in inspector
Code at least
well look at your code
you are playing the audio every frame
when the health is below or equal to 0
its a death sound
and you are playing it every frame
Basically what you wrote is
every update meaning every frame your music will play
ah
if health is below 0
learn events
make OnDie event, trigger it when unit dies
and subscribe stuff to that event
I assume you expect the sound to end when the object is destroyed, which is fair. However, you destroy it after the length of the sound has elapsed, and considering this code plays every frame it will invoke the sound every frame until the first Destroy call has its delay end
So instead destroy it immediatley and have the sound play on a separate gameobject, maybe
Or add a boolean to indicate this if-statement has triggered
Actually i wondered same too, even tho im not beginner
Depending on having a gameobject destroy itself so the update statement doesn't trigger is kinda bad to begin with
Like detect in update, and then run only once
perfect event use case
How can you do that
A boolean variable?
things like that shouldn't be handled in Update
I usually have a SoundManager empty GO that I use for all my sounds for this reason
Having it in an Update statement is the actual problem though
It should be an event handler
I agree
what is event handler
dealDamage should trigger an event that indicates the object died, or instead that it took damage. Then have another script handle the sound if the health reached 0 or lower
Look up UnityEvent 
well
aight
i just said that 3 times already π
My bad
Or make the simple fix of checking health in dealdamage if you don't want the added abstraction
And it only runs once, correct?
Maybe consider evaluating and setting the object for destruction after decreasing health.
And please consider using proper .NET conventions when writing code. This is pretty bad...
Imagine how life would be easier if discord also included line count
BetterDiscord has a plugin for that
It's called Enhance CodeBlocks
I don't think BetterDiscord is going to fix a screenshot
Nice one haha
Hi guys,i have a question,i have to draw a vector but rotated,how can i do it?
i have to rotate it of 180 degrees in the x axis
Depends how you want to rotate it
My question is can i do it?
Yes
Quaternion.AngleAxis or Quaternion.Euler
Multiply it by a quaternion that expresses the offset you want
Here take this graph
Good graph
Can you give me an example
thanks
What's happening instead?
100%
π΅βπ«
It sure does
anyone know if there's a way to reset rich text in a string? like if the first part of a string is in rich text but I don't want the next part to be and I don't necessarily know what tags that were used so I can't just close them (user provided)
I have simple action map for UI and EventSystem component set up with Input System and it works just fine, but when I disable this action map - it still register input to IPointer_xxx_Handler and its callbacks being called just as it was enabled, but it's not
am I missing something? why its calling this callbacks even when action map is disabled?
string nonRichTextString = Regex.Replace(richTextString, "<.*?>", string.Empty);
was afriad of that... was hoping for a more supported solution like a reset tag of some kind
Afraid why?
well, any robust solution would have to be much more involved than just that
Regex is not that bad, just don't do it inline like this
Because this is slow
There are libraries that can generate code to replace a regex query, I believe it's even is base .NET
I would just prefer not to use regex as there's always a chance it'll capture user input unintentionally possibly without a means of escaping it
You could make a list of all the rich text tags and replace those with nothing
but I had seen a few use it as a solution on forums so I was fearing that was the only way to solve it
Consider, two parallel fields, one with rich text enabled, the other not?
but the text needs to be side by size so I'd need to adjust it using horizontal layout? idk how that would even work with multi line inputs
You mean users writing something using < and >? I know base HTML formats user based characters like these as to not conflict with actual tags, I'm not sure if Unity does the same
I don't use UGUI any more, so I have no good answer for that one lol
UGUI?
Unity UI
ah
I was just hoping that you might have a simple enough case where it would not be bad
tbh I'm considering just disallowing all rich text with the noparse tag. but this is more if I wanted to allow it in the future
unfortunately not. I could limit the size of the first text but the second text is of unspecified size so it can span multiple lines to fill out a container
dafuq does that mean
- every time i try to join the multiplayer game i created it crashes as soon as it loads into the map
thats also a error i am getting
i am super confused since this is not telling me anything
This multiplayer right?
yea
I would have thought
Disconnecting connection: connection(0) because handling a message of type Mirror.RpcMessage caused an Exception. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: System.Collections.Generic.KeyNotFoundException: The given key '5' was not present in the dictionary.
was more than enough information
I can't post invite links here, but you prop want to go to the "Unity Multiplayer Networking" server. It's generally more helpful.
could you dm me the invite?
hello im having troubles with making scripts for each level of difficulty of the game we're developing, can someone help me? π₯Ή
we're currently developing a game and our game is inspired from decked out 2
you may or may not be familiar with the game, but its a good one!
After 13 months in development it's ready! The ultimate dungeon crawling, deck building, treasure hunting game build in survival Minecraft. Learn how to play Decked Out!
βΊ Subscribe to my second channel for all Live stream replays and alternate content
https://www.youtube.com/c/TangoTek2
βΊ Follow me on Twitter for all announcements!
www.twitte...
Never heard of that particular game, though what issues are you having? If you have specific questions, im sure someone may be able to help (though it is quite late in this part of the world, so it could be some time for others to see your message, generally though, more details are better to help with)
So in our script 'HardDiff.cs', which is the script for hard-coded parameters for every dungeon (based on thei difficulty), every difficulty has different parameters. We're gonna put it in a single script for button event in onclick(). Now, we will inherit those parameters from different scripts such as RoomFirst script, RWalkDungeon script and Abstract Dungeon script. The RoomFirst script, is for the room and dungeon partition, then RWalkDungeon is for random iteration and the Abstract dungeon is for clearing the dungeon every generate.
So the predetermined parameters are:
Easy
Min Room -W - 10
Min Room - H - 10
Dungeon - W - 70
Dungeon H - 70
Offset - 2
Iterations - 50
W Length - 15
Medium
Min Room -W - 20
Min Room - H - 20
Dungeon - W - 150
Dungeon H - 150
Offset - 3
Iterations - 100
W Length - 25
Hard
Min Room -W - 20
Min Room - H - 20
Dungeon - W - 250
Dungeon H - 250
Offset - 4
Iterations - 200
W Length - 60
The issue is that there is a script 'DungeonData.cs' which is for the parameter editor for RWalkDungeon. We made a 'Hard' button to try. But it wont generate a dungeon.. here's the code.
here are the parameter script for RoomFirst script, RWalkDungeon script, Abstract Dungeon script, and DungeonData.cs
One suggestion I can make, if you want to simplify some of your repeat variables across the various scripts, you can put them all in a class, if you serialize that class you can populate it from the inspector, and if you put that serialized class into a ScriptableObject, you can even create assets of that data to reference on various objects, for example:
[System.Serializable]
public class SomeData
{
public string name;
public int health;
public float speed;
}
[CreateAssetMenu()]
public class SomeDataSO : ScriptableObject
{
public SomeData data;
}
public class SomeImplementation : Mono
{
public SomeData data;
public SomeDataSO so;
void SomeFunc()
{
Debug.Log(data.health); //assigned from inspector
data.health = so.data.health; //assigned from asset, referenced from inspector
}
}
This alone wont solve the issue you described, but it may help just having to only add "SomeData" to scripts, or referencing just a "SomeDataSO" in case your designers wanted to change the numbers at any point without having to dig through specific objects and scripts
okay will try that right away, thank you!
For future reference, it's pinned to #archived-networking
Hello, does anyone know how can i crop extra alpha pixels in a Texture2D in runtime, akin to Trim option in Photoshop?
I need to do that to preview the images, because otherwise the full image is going to be scaled down and hardly visible
At the same time i can't change the source image, because it's used in full for overlaying purposes
probably more efficient to just make 2 images
Yes, i'm considering this ATM, i was just wondering if cropping would be a better option, so i could keep the image clutter minimal
Thanks for responding!
it's not difficult to do but it is time consuming
you scan the pixels and make a bounding box for the non alpha pixels then you make a new texture and copy the pixels inside the bounding box into that
hey, is there a way to make tab between input fields ?
so essentially i need to find pixels with value not equal to zero and go from there?
alright, thanks!
if this is for something where you can use sprites, you could also look at doing this in the sprite editor? so you create a sprite of the middle part not including the transparent border, then use the full image for the overlay
i'm afraid not, the images are not stored in the project
you can create sprites at runtime too actually - you just need to give it the texture and rect
i don't really understand the benefit of this if i'm working with just the texture
but thanks for the suggestion
you haven't specified how you're displaying the images, but it'd be a benefit if it was a UI Image or something like that, because creating a sprite would be cheaper than copying a whole texture
they mentioned sprite since you can define a rect on a texture of the part the sprite should be of
though first thigns first how are you wanting to use this texture?
if you wanted to trim a texture and not make a sprite on it, you would create a new texture of the target size then copy only the pixels in the range you care about to it
the original texture is added into the template, so the output would be the combined texture, that is then used for an image
in the end a sprite is just a way to tell it to render the texture with the right UVs to display a region of the image, so whether or not you can use a sprite, that's an option if performance is important
via a sprite renderer?
UI image
you want a sprite anyways then
yes, but isn't that a final stage though?
since UI image does not use texture directly, so you can simple create a sprite that displays 1 area of your texture
i simply don't know how to make this to be honest, so i'm just tinkering with the source texture
if you are deadset of doing it in the texture, there is no trim function, what you do is create a new Texture2D at the wanted size, then copy what you need from the old texture into it
https://docs.unity3d.com/ScriptReference/Sprite.Create.html
the sprite method for this
doing it the texture way is a little more complicated
The trick is to calculate the Rect, what you do with it, Create Sprite or make a new Texture is not so important
i see, thank you for the help, i'll try to figure it out with what you provided
Hey guys, can you teach me how to make a player teleport?
I tried tutorials on youtube but didn't work.
transform.position = newPosition;
If it is possible, can you make a vid?
he literally gave you the code
I'm just trying to make a player controller with netcode and the character keeps bouncing at extreme speeds into the stratosphere
teleporting is just setting a position instantly
Yeah how to i apply it?
you put it in your code at the point you want the player to teleport
think you maybe should work on the basics first and learn a little about how C# and Unity work
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.VisualScripting;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Processors;
[RequireComponent(typeof(CharacterController))]
public class PlayerNetwork : NetworkBehaviour
{
CharacterController characterController;
[SerializeField] new Camera camera;
bool isSprinting = false;
void Start()
{
characterController = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
}
public float moveSpeed = 1f;
public float sensX;
public float sensY;
float xRotation;
float yRotation;
float horizontalInput;
float verticalInput;
Vector3 moveDir;
Rigidbody rb;
private void FixedUpdate()
{
MovePlayer();
}
private void Update()
{
if (!IsOwner) return;
//Camera controls
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
//movement
MyInput();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
//calculate movement direction
moveDir = transform.forward * verticalInput + transform.right * horizontalInput;
rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force);
}
}
it's using netcode as well btw
!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.
please use something like hastbin for large code snippets
and don't scale mouse delta by deltaTime https://unity.huh.how/mouse-input-and-deltatime
I do know how unity works. Only abt the coding i get stuck with. I take all my code on github or youtube tutorial
so you blindly cpoy/paste code
without understanding it
right
Yeah...
you are asking for a video on how to set a objects position, that is like the first thing people learn
and you think it's a good way to learn things?
I'm still learning coding at schoolπ
like i am not trying to be harsh, but you have to put the effort into understanding things to use it
Aight.
all introductory lessons on unity and C# will show you how setting positions works which is what a teleport is
and such followup questions should be in #π»βcode-beginner
I put the player in a box and it got worse
https://youtu.be/WY4EHUO_Je8
Can I set the "Build Configuration" and "Script Debugging" parameters in the build settings tab from script? I've been looking around EditorUserBuildSettings/EditorBuildSettings/PlayerSettings and I don't seem to be able to find anything relevant. I did find the necessary development flag I need to enable script debugging, but not the actual flag
hey is there anyway to make the tab button switch between input fields ?
i think you have to do the input handling for the tab key yourself but the field switching is something like this:
var selected = EventSystem.current.currentSelectedGameObject.GetComponent<Selectable>();
if (selected) {
var next = selected.FindSelectableOnDown();
if (next) {
EventSystem.current.SetSelectedGameObject(next.gameObject);
}
}
I don't see any reference to Script Debugging or Build Configuration settings here. I'm also hoping to not have to launch a build, just toggle those settings. The development flag can be set with a simple:
EditorUserBuildSettings.development = value
I'm hoping to find these values similarly without having to launch a whole build
BuildOptions has the Development and AllowDebugging properties but I guess you need to use BuildPlayer via script to use them
EditorUserBuildSettings.allowDebugging was exactly what I was looking for thanks. I was looking for the words they actually use in the GUI like an idiot
Still need to find that Build Configuration setting and then I can close this task
do you mean the activeBuildTarget and the various subTargets ?
I am moving my project folder with my unity project from a mac to a new windows machine. Is there anything I should know to ensure a smooth transition?
best to use Export/Import
What's a good way to move the player other than transform
wdym
Unity hub has an βadd projectβ button to add project from folder
but that sounds like a different feature
Asset->Export on Mac to create a .unitypackage Asset->Import on Windows to read said pakage
gotcha. and this is on UnityHub or in UnityEditor?
Editor
there is no need to export
just delete the library and temp folder after copying the project folder over
i just want to send over to ensure as smooth of a transition as possible
yeah jsut copy the whole project folder and delete the Library folder in it
i assume an explicit export/import is designed to handle that
iβll give each a shot. The only thing I have to lose is a little time
at work we are using a mix of macs and windows and it all works fine. using git which ignores the few folders that are generated by unity and its all seamsless
Refer to Unityβs gitignore template to see which folders are useless.
Itβs as simple as copying over only the actually useful ones and just open it on the new machine, nothing much else is needed.
even i have both machines on a kVM and swap between on the same project at times based on what i am building for. like need windows to build for switch for example
also i heavily recommend learning about version control and Git
ty. Iβll need to check it out
i guess on a different note, letβs say I have a mac and a windows PC, and I want to be able to interchangeably work with either on the same project. What is the best way to sync everything?
github?
Any version control.
which would you recommend?
I havenβt done ssh since my college years
donβt even remember what it stands for. just have that memory lol
no need to sync anything, make a shared drive on Windows or Mac and just use the same project
really once the ssh key is setup its not something you have to worry about again
I personally use git yeah, but supposedly it doesnβt work that well for large binary assets. My projects donβt have a ton of large assets for me to really know if thatβs true.
i setup the ssh keys for git on my mac like 5 years ago and never touched it again
@knotty sun shared drive would be very bad for this due to the Library folder
local repositories for larger assets
would need to nuke it everytime and let it regenerate which is a waste of time
i see. is there a guide/resource/tutorial on how to best set this up?
i think you are saying to set up a git with an ssh key.
works for me, I have the same project being used on Mac, Windows and Linux all from one shared drive
they probably all do work. but version control is probably better to revert
For git, it shouldnβt be much different from other projects. Have your credentials setup, have the Unityβs gitignore template setup, then just commit/push/pull/etc like you normally do.
you should have version control whatever else you do
yeah, Iβve been bad
you get other bonuses with a full VCS system too, since you can revert to past versions easily and see diffs which makes tracking down bugs much easier
are there any privacy issues?
can work on features in isolation from other changes and easier collobration
depends on where you host it, but pretty much any provider will have private and public repos
only, if you use Github, MS will steal your project to train their AI models
Also to note git is not tied to GitHub/GitLab/other hosts, you are free to use git completely offline or self host if you want.
so i should use git
yeah git is the system and protocal GitHub,GitLab,Bitbucket etc are all just cloud providers for the remote
some people might recommend unitys vcs system, but i greatly prefer Git, and its the standard for most software development these days
gamedev and animation are the main exception where Git is not the defacto choice, but still common in this domain
cough
Use a rigidbody
that is not really a good question unless you say what your intent is and why you need to move it in a other way
ty all.
like if you want to use physics use a rigidbody, if not use a transform
How do you use a rigidbody as I tried that and it didn't move
rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force);
i got a climbing script in unity for VR but it should be the same as for 3d just the hand being the player so im asking this here and i have some issues with it.
the first issue is that if i start climbing on a object i get teleported a little before my hand is at the position it should be again.
the second issue is that its responding too slow. its smoothing my movement out which it shouldnt it should be moving my player exactly when im moving my hand too.
this is the part that is handling the climbing which is in my FixedUpdate() void:
Vector3 deltaPosition = currentObjectClimbingOn.position - lastHandPosition;
rb.MovePosition(rb.position + rb.transform.rotation * deltaPosition * 10f * Time.fixedDeltaTime);
lastHandPosition = transform.position;```
i already tried removing the Time.fixedDeltaTime and also tried changing the multiplier from 10f to something like 100f or 1f but with 100f or no Time.fixedDeltaTime im getting flung around and with 1f the movement is even slower.
thanks man it worked
Does it need collisions?
yes
Oh seems like you are trying a rigidbody already
Hi! Do you guys have any idea for pdf generator in unity that can work on android?
Yeah, I've got this rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force); Physics.Simulate(Time.deltaTime); (surely this doesn't count as big enough to be put in hastbin) but it doesn't seem to do anything and I don't know why
is your rigidbody dynamic
no
^ Also why are you calling Physics.Simulate manually
also you should not need to call Physics.Simulate unless you have an extremely good reason to, which you donβt
the docs said something along those lines
well, Iβm telling you no
Physics.Simulate runs the entire physics simulation by that timestep
play still can't move
Which doc π€
This?
Unity by default runs Physics.Simulate(fixedDeltaTime) at the right time, every fixed frame
do not call Physics.Simulate unless you are making a custom physics system or something.
rb.AddForce(moveDir.normalized * moveSpeed * 10f, ForceMode.Force); I have this in void Update but nothing happens and I also have this for input system if (Input.GetKey(KeyCode.A)) horizontalInput += 1f; if (Input.GetKey(KeyCode.D)) horizontalInput += -1f; if (Input.GetKey(KeyCode.W)) verticalInput += +1f; if (Input.GetKey(KeyCode.S)) verticalInput += -1f;
- If your rigidbody is not dynamic, adding force will never move it
- you have not checked if the vector going into Addforce is non zero, which is a separate check
does this mean setting collision detection to continuous dynamic
for 3D, not kinematic means dynamic
check the vector being passed in to add force
with Debug.Log
if the vector is small or zero, that needs to be resolved first
and the script is on a monobehaviour on the object
and the addForce is in FixedUpdate
the script is NetworkBehavior
but does it derive from MonoBehaviour
sorry this is a WSA setting I can't find... Build Configuration it swaps between Debug/Release/Master
no its from netcode
but also I control clicked it in visual studio and the file defining it was monobehavior
before you try importing any code into unity, you should at least know the basics, man
you donβt know how to drive, and youβre on the highway
I can still walk confidently
start by writing code from scratch without importing
I mean I did a bit of that
you should be putting the whole script in hastebin tbh
I gtg now but thanks for the help!
so i got this track that i made with splines out of a prefab which looks like a hollow cube, but i noticed that there are overlaps between tracks in narrow parts, and large gaps in sharp turns, so i reduced the distance between them and tried to link the vertices with probuilder but i later realised when i baked the instances that there are more than 150 instances that i need to link vertices of, and not only that but you can't "Weld Vertices" of two different gameobjects anyway, so i am asking here is there a way to link the track visually in a way that 1. won't need me to join between gameobjects (because i have some logic that uses the rotation of each gameobject and it's transform.forward to determine camera rotation) and 2. something that wouldn't need me to go making an algorithm using the Mesh class and merging vertices that way since i don't know a lot about it and it can break in a million ways with normals, lighting, texture etc...
dont crosspost
I'll delete the previous one
Hello! I am trying to make my Enemy detect the Player using a Spherecast, but it doesn't seem that the Spherecast is hitting the Player, because I'm not seeing the Debug.Log() message. In the screenshot, the transform gizmo is the origin of the spherecast (raycastOrigin.position in the code), and where the arrow i drew points to is the origin of my Player (player.transform.position in the code).
raycastDirection = raycastOrigin.position - player.transform.position;
if (Physics.SphereCast(raycastOrigin.position, 0.05f, raycastDirection, out hit, raycastDistance))
{
if (hit.transform.CompareTag("Player"))
{
Debug.Log("<color=red>Enemy sees player!</color>");
result = true;
}
}
Guys lets's say that a person uses the method LookAt() but looks that target objects with the back of the head,how can i look the tarket object with the front of the head?
I think you already know the answer, it's the one you're so desperate to avoid. It's really not as hard as you make it out to be and for the rotation, you can get it from the spline instead of per-game object. You'll get smoother results anyway.
- check the tag
- check what the spherecast hits, player or otherwise
Joining game objects and welding vertices or using the mesh class? Also how can I get it from the spline, that was originally what I wanted to do but I couldn't find a way to get rotation at x,y,z position. And I tried with spline animate but I still couldn't get such properties
- spherecast only returns 1 hit when you want a boolean output
so if you have multiple hits, and the first one isnβt the player, but the enemy, it will return true with a hit of the enemy
also, your spherecast should restrict search to relevant layers
Generating a mesh dynamically.
I don't know the unity spline system but generally you break down the spline into a polyline with smaller segments who's lengths are closer to even. It's useful for navigating the spline at even speed if you're using the actual spline for navigation.
You can get the spline's forward vector by sampling the spline/polyline at ((p + some small value) - p).normalized. I'm sure unity already has something for this tho but I can't speak to it.
as for the mesh generation, under its most basic form
- sample all points (or break down into polyline and figure out the target length for the resolution you want)
- figure out the width you want, find the forward vector at the position of point and create verts at -perpendicular vector * halfWidth, another one at perpendicular * halfWidth.
- If you want your road to have thickness, offset 2 more vertices based on those vertices and the relative up negated
- repeat for all points
then just read the mesh generation doc, it's like a 5 minutes read, it'll explain the order of triangles and a few more things that are really simple to grasp but seem scary in nature
Thanks. The raycast was hitting the Enemy's eye. I have now set those' layer to Ignore Raycast, and my freshly created Debug.Log() confirms that the spherecast isn't hitting them. It now appears that the spherecast is going in this direction:
yeah, I would use a method that returns a list of RaycastHit, and then sift through to find valid hits
I would also include a layer mask, because the enemyβs eye should be on a layer that does not get included in your query, probably
Thanks
when you have a regression and then notice you have no idea why it occurred because your code is spaghetti...
i hope everybody is ok with me sharing my stupidity
You probably have the wrong pivot
eg your Forward is wrong
make a parent with the correct pivot, rotate child until matches correct pivot
show your current object, make sure Local / Pivot mode is selected
Can i write you in private?
no but you could make a thread here if you want
How can I exclude an object or component that is part of a prefab from being recorded as an override?
iβm not sure what the use case is here
itβs in the prefab, so you want it to come with the prefab. But you want to make edits to it, and not log that it is editted?
I have instanced materials on the object that need to be unique per object
So as soon as I add the object to a scene it comes with an override
What's the issue with it having an override?
That it makes the object appear to have been modified in the scene, but by nature it will always appear overridden
Also I assume you mean when you add it in the editor? I guess you have an editor script doing the material instantiation?
Yes
Well it is overridden...
why
But then the material change won't be saved right?
so I can more properly track prefabs that have been truly overriden
to not be overriden means it matches the prefab
but you did override it
but it can't match the prefab because the material is instanced on the prefab
so it will always appear overriden
i just donβt understand what the issue is here
it is overriden, because you did override it, and that it why it appears overriden, because overriding is what you did
i feel like Iβm talking to patrick star
The issue that I would like to ignore specific overrides, I'm not asking you to understand the specifics of my project
Hi I'm working on my own custom input tool that builds on top of the input system that uses scriptable objects as events. Now conventional wisdom says that I won't be able to do exactly what I want to do without some sort of grouping (list, array, etc...), can you loop through every reference of a type of variable in a script? I want to use it to automatically generate the event scriptableobjects. In essence I want the function to go through these variables in the image below and create an event object with the same name and then assign it.
being able to know when an object is overriden is useful but this specific prefab will always appear overriden and it's an override that I don't care about
you mean you want to be able to modify the prefab, and propagate it only to specific instances, based on the contents of the material field?
then whatever editor script you made needs to explicitly check for that. probably OnValidate
put them in array
Yeah that is the obvious answer, just wanted to see if it was viable without
you are asking for Unityβs prefab system to propagate changes in a way that is more tailored to your specific use case, which diverges from the standard
and that is ok, but that requires specific code for it
use Reflection
i think I would use a singleton non-SO
storing events in an SO during runtime for transient input events sounds like bad juju
Reflection would allow you to iterate over all of the members of the type, yes
I have a vaguely similar situation where I need to both have specific fields and have a list of all of the things in the fields
in that case I just accept the duplication and make sure I put things both in a field and in a list
(I have an editor script that verifies this, through reflection)
Yeah cuz putting it into a list makes things a lot harder in general
I could probably just switch to using reflection at runtime.
reflection is the way to go here
TypeCache should be faster than reflection, use that instead of reflection
assuming it's for edit-mode
anyway, the bigger thing is: you probably donβt want to use SOs for this
it's way beyond that, it's natively cached
another unity bug (i think so?) that makes making this door even harder
So long as there is a reference in the scene then all the function run fine
im slowly starting to hate this game engine
What exactly is the bug here ?
look at limits
when I de-active element and re-active it
limits are relative to current local rotation
you can't imagine how long i've been debugging it for
Hmm that does indeed look like a bug. File a bug report for it
where can I do that?
π
usually when people say that, they will still using it for years
Sounds like your player model is just backwards, better fix that
Oh sorry I was scrolled up
I'm already going crazy
the same script that perfectly found the object I want, it says it doesn't exist
how is this possible
HOW find something that doesn't exist
probably a copy then ?
I hope so
it suits best my game and there's nothing better (maybe unreal but for graphics)
I'm using both for work, UE ain't as nice as what you're seeing or heard either.
I tried to delete it and even everything from scratch again, it still has the same problem
Type "t:RadioSystem" in your hierarchy search
That wouldn't help with a copy of course
I know that, for me it has only good graphics but its not that good for games
only one
show radio system script
RadioSystem.cs//InterectSystem.cs
π 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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
ok
!code public void OnClickInterectEvent(GameObject ObjectSelected)
{
if(ObjectSelected == radioObject)
{
Debug.Log(radioObject);
cursorDetectorScript.SwitchCamera(5);
RadioTutorialCanvasAnim.SetBool("TurnOnRadioAlarm", false);
radioInterect = true;
}
}
π 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.
I didn't understand how "!code" works
π 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.
did you actually bother reading the fucking message that was sent 3 times already?
no, I'm in a hurry, I need to get out of here in 8 minutes very sorry
then come back later to get help
but thanks for letting me know
ok bye
When you come back, we want the WHOLE script. Use a paste site as described at the top of those messages
if a rigidbody is restraining rotation of an object, how can I make a script follow these constraints as right now it is just rotating freely
The constraints only stop rotation from forces
But not from you moving it
how can I change that
You cannot
You just have to clamp rotations yourself
can I rotate it through the rigid body
If you have a rigidbody, yes you should rotate it with the rigidbody, and ONLY the rigidbody
how
because I tried rigidbody.rotation but it was still not following the constraints
I'm almost certain it does not, but it was a while ago that I tried
AddTorque does at least
it doesn't
Other option is rigidbody.rotation
And yeah, AddTorque
They tried it
Oh, they asked how to rotate with a rigidbody, so I didn't think they tried anything, and instead did it with transform
how do I turn my quaternian for rotation into a vector 3 for addTorque?
euler
Quaternions have .eulerAngles
Note that you shouldn't just plug in the target rotation in it
You need a difference from your current rotation to the target rotation
Just like you don't give AddForce a position, you give it a direction/force vector
would it be easier to just clamp it?
you havent even explained your usecase, how can we know whats better /easier solution
it's a playercontroller with a rigidbody
Just to make sure - it doesn't have a CharacterController component right?
It did but it seemed to make the character go flying randomly
Yeah rigidbody doesn't work with CC
well yeah its collidng with rigidbody (making rb fly off)
Yeah, they cannot be used together
found that out the hard way
How do you move normally?
they are different physics objects thats why
AddForce, Velocity, or MovePosition
This is probably a valid option tbh
rigidbody.addforce
Try MoveRotation with clamped angles
MoveRotation respects interpolation while rotation does not
I'm not sure how to clamp the character without clamping the camera because it's first person
wait nvm
does anyone have a good solution for hiding changes to files that need to exist in the repo but that do not really want to have changes made but for which unity makes changes often (eg, a material which has a property set in play mode) - technically we could clone the material but its kinda a pain to update references since its used in a ton of places. I previously wrote an onquit script to revert it but it looks like that has broken. I'm thinking of trying git assume-unchanged or git skip-worktree
``` Why can't I do this and how would I clamp the x rotation of this object (camera)
so, two things
transform.rotation.x is not an angle. It's the X component of a quaternion.
and that's an error because transform.rotation is a property, which returns a copy of your current rotation
modifying this would be pointless, so you get an error
so how would I do this
I would suggest storing the desired rotation for the camera in a float
I can't seem to see a channel where I would ask about Muse Behavior so I will ask her and anyone can just point me to the correct channel.
I am currently trying to learn how to use my own sysorySystem script with the muse Behaviour tree. I keep getting a null reference when trying to gain access to the script.
Any info, links or tutorials on the topic would be highly appreciated .
You can try to clamp the euler angles of the transform, but this can cause some unwanted behavior
for example, -30 and 330 are equivalent
So you might wind up being unable to look down if transform.eulerAngles spits out 330 instead of -30
instead, store the desired pitch (X axis rotation) and yaw (Y axis rotation) as float variables
then just set your rotation directly
well all I need from this script is to stop my fist person player from looking too far down or up
transform.rotation = Quaternion.AngleAxis(yaw, Vector3.up) * Quaternion.AngleAxis(pitch, Vector3.right);
that's how I do it
I think Quaternion.Euler(pitch, yaw, 0) would also work but I'm not 100% on that (maybe the order of operations will be wrong?)
muse behavior tree ?
someone's actually paying for that?
It's free...
i was trying to read about that
typical unity
i could only find a really trivial example
release half-baked features with no to little docs
I just need to figure out how to gain access to scripts
The NPC is fully patrolling already
hard to know what the methods are withou docs π€·ββοΈ
just need to learn to get access to my scripts via blackboard keys
true
there are docs though
link me
1 sec
It is also free to use
I have no subs
Muse AI needs a sub but this does not
The AI I am building is rather complicated and behavior trees seems to be the only option
also you need to show which line of the script is throwing you NULL
well yeah behavior trees are quite complex
My bad.
you did not assign SensorySystem a variable name
It was correct here
SensorySystem = // stuff
instead of SensoryStem sensorySystem = // stuff
I thought so to but it through the null
well you certainly dont fix a null by removing the variable name xD
Agent or Value is null then
again, I thought I would assign it like the others as a blackboard
That's not it
Value is null though
so I assume
we don't get references like that
"thats not it", meanwhile Value is null lol
go for it if you'd like
trying to find something more in this package
same, I am struggeling to find actuall examples
I have this.
I can look into it and study it up I'd be interested in exploring this example maybe video it
I gotta run out for a few hours so can't look till later
THis is where I got the idea
from that example
the animatorObject.value.GetComponent
Yup
you watched the video as well right?
Explore Unity's "Muse Behavior Pre-release" in our tutorial. Learn to animate guard NPCs with this innovative AI behavior tree system. The tool, still in its experimental phase, offers a visual, graph-based interface for easy AI implementation, including behavior trees and state machine logics.
Understand node-based AI behaviors and their real-...
Yup They don't use external scripts
so I guess I am stuck with find
will try it out and see if there are better ways later
the future is here!!
I mean it works fine, just find it funny that unity does the things they recommend others not to do
having difficulty rotating camera https://gdl.space/ixexijoput.cpp
also show your !code properly when asking for help. showing it in a video is one of the worst ways to share it
π 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.
sorr
I am using Physics.OvelapBoxNonAlloc to detect something while trying to avoid the garbage allocation.
private static Collider[] hitResultsBuffer = new Collider[1];
Physics.OverlapBoxNonAlloc(position, size, hitResultsBuffer, Quaternion.identity, LayerMask.GetMask("Enemy"))
But the second line do allocates a garbage! Is it normal? Allocation is 40B but it can stack up so i cant dismiss that. Am i using that method wrong?
It seems something wrong in native side
It will be the GetMask call allocating it
GetMask takes a variable argument list
C# handles that by creating an array
cache your layermask
what's wrong?
You have an interactor component in your scene that doesn't have a point assigned.
it does tho
The variabe _interactionpoint of interactor has not been assigned. You probably need to assign the _interactionpointvariable of the interactor script in the inspector
The one you showed does. Doesn't prove there isn't one out there that doesn't.
wow that's helpful
you have more then 1 of these in your game
Indeed! It tells you exactly what the problem is and where to look!
or something destroyed the object its referencing
that's the only thing that has it
How did you verify that to be true?
Screenshot your unity window with t: interactor in the hierarchy search window, after the game begins and the error appears
because you put it there
ooh its from a diff tutorial
So unity has UnityEvents which work really nicely, and can be invoked, and from the inspector work in an awesome way where you can just load up any number of functions an event
I'm wondering if it is possible to do a similar sort of thing in the inspector but with a variable rather than a function
To maybe help make it more clear what I'm trying to do, is something like this image below, but instead of the "Value" being a bool check mark, it is a selector where I can select any of the public variables from the above script. is anything like this possible?
like see how an event works with functions and a list, i really would like to be able to do a similar thing with variables
how to handle persistent ID for prefabs between scene loads and maybe game sessions? I can't figure it out for non very bad or sloppy way of achieving it
Events work with properties as well. Just turn your variables into properties and you can set them via UnityEvent
what do you mean by properties? like class variables? do you know of any examples?
What is it your trying to do, where you need to persist a prefab across game sessions? For scenes, you could probably put the instance in DDOL so it survives scene loads, or store them in a list inside a scriptable object or singleton, and pass the index to the next scene so spawn a new prefab of the same type
Intersting... I'm not entirely sure that helps my case as UnityEvent was really more of an example than what I need
Basically what I'm trying to do is have a list, like a UnityEvent, where I can select variables/properties on a script and their state. I'll call this list like "requirements"
Then, I need to go through the "requirements" and see if every variable in the list meets the chosen state... I assume that a property in an event is calling set and not get, right?
I basically need it like this, but instead of setting Test to false, I just use get and return true or false if it is equal to what I have here (unchecked, so false)
Idk if that makes any sense lol
is there a way to export the way the bones in an animation move mathematically?
ie what transformations were applied to the bone
I'm bad at explaining (and made a mistake when I typed my last message, I meant only between scene loads, not gamesessions, lol)
I want to store a UI data between scenes separetely from my UI elements, so I can just put my old state into new instanced prefabs of my UI views and it's ready to go
I can't just use type as key, because view elements can be multiple of the same type but different in data values (like labels and buttons)
for data store I've used scriptable objects, yes, but I dunno what to do with loading UI elements of the same type and different data associated with them, so I was thinking about GUID or something similiar, but I can't figure it out how to setup it's generation properly
If Im making something like a conveyor belt to move an object that is touching it, is it best to
- add a small amount to the position every fixed amount of time
- set the velocity of the object to a certain amount
- add a force to the object
i dont get it
Your method is not declaring a body, you have a semicolon here.
The next error is probably telling you that the { is unexpected.
ah
Ah I see, static variables exist in memory so their data doesnt rely on the state of scenes, and ScriptableObjects exist as assets in the project, which also doesnt rely on the state of scenes, however you can also create ScriptableObjects at runtime as instances, which are not files yet, and exist in memory, which also means they can persist across scenes, so any of those 3 options could help if im understanding what your trying to do correctly - with a GUID, I think that might be a bit overkill, though youd want to make sure you only register the GUID once for that object when it is initially created, and then store that GUID in some kind of static list or file so it exists in memory or accessible through System.IO, then you can read that file on the next scene or access the static list and compare the GUIDs in the list to your prefabs matching the same GUID, though that still uses static where the former may be a little less involved to implement imo
Ok I have anotehr question similar to earlier lol... is it possible to
a) have delegates show in the inspector, or
b) have unity events return a value other than void
unity events can pass data
you can have a UnityEvent<int> for example, and when you invoke it can pass it int into invoke and all subscribers will get it
I'm thinking more like, a UnityEvent which has X functions loaded in it on invoke, then if all of X functions return true, the event returns true, otherwise the event returns false
I know thats a little weird, which is kind of why I thought delegates would be my solution, but those don't work in the inspector AFAIK
yeah not something you could do in the inspector directly
i kind of need it to be for what I'm doing lol, otherwise ill have to hard code so much stuff... do you know of any alternatives to what I'm thinking? i just need a way to have the functions, or even variables, that the event/function is checking to be determined in the inspector
interfaces, or abstract classes
reference objects that have a common interface method to call for it
Reference the component and implement how they'd interact through script.
really virtual or abstract methods on a common type would do it
since they you have your list of them, and can loop and get the return from each one when calling the method
and that can be assigned via the inspector?
yeah since you are just dragging in a regular component reference
they all just share a common base type that has a abstract or virtual method
so if im understading this right, i do a virtual function, say CheckRequirements() and then use an interface to add the inspector functionality? sorry if im slow here ive never used interfaces before lol
well due to a quirk of unity you cant use a interface for the part in the inspector
so would give all the things that should have CheckRequirements a common base type
that has the virtual method CheckRequirements they can override
The things running CheckRequirements would all be on the same script, but the functions to be loaded (to be checked) wouldnt necessarily
well
yeah that is hte idea
alright then I guess im just not understanding which part enables the inspector aspect lol
the thing calling CheckRequirements would have a list of BaseRequirement on the inspector
then anything extending BaseRequirement can be put in that list
and each of those things can override and define there own CheckRequirements methods
okay im understanding what you mean now, but I'm not sure thatll solve my problem either cause the classes i'm looking to get the data from wouldnt be extending the one with CheckRequirements, they are MonoBehavior
Make them extend the CheckRequirements...π€·ββοΈ
ok its gonna take me like an hour to wrap my head around this but i think this might be what i need
thank you
yeah not fully sure what you are trying to do, but that is one way of doing it
instead of needing to manually drag to the list, also would be doable to just have each requirement as a component you add to the same object then on Awake you get all of them at once save to a list then use that to evaulate things later
so in your example, you are putting SomeReq into the list of BaseReqs right?
What if I needed to have a list of BaseReqs, then something reference BaseReqs, then my SomeReqs reference that something
So like here is my kind of layout
I have an Interactable (contains CheckRequirements())
then I have BaseReq
then Bucket : BaseReq, this has property isFull
then I have a Bucket_IsFull : Bucket, overrides CheckReq to return the isFull propetty
but I cannot put the Bucket_IsFull script into the list of BaseReqs
SomeReq can is stored in list of BaseReqs
anything virtual/abstract in BaseReqs can be overridden in the stuff extending it
and when you call it, you will get the overriden version
and what about a double dependency
like for me it basically goes BaseReq<--Bucket<--SomeReq
i can't just go from BaseReq to SomeReq unfortunately cause I have properties in other scripts I need to reference, like the isFull in my bucket example
thought you would just check that in the overriden method to decide if it returns true or not
like the things extending BaseReq can be what ever you want, they just must implement its abstract methods
and you can have multiple thigns in the inheritance chain though it would recommend not making it long and complicated
does anyone know why my events either lose reference or get unsubscribed after being serialized or say after you make changes to script and unity reloads
are you referencing scene objects from non-scene objecst? those references cannot persist beyond playmode
anything you reference in a prefab much be within that prefab, another prefab, or an SO
No, I have a class that contains visual data (color, texture etc) when I change the data of said class (change color for example) an event if fired, detailing any meshes that uses that class data to update
the problem is that when I make changes to the code, that event is unsubscribed and I have to resubsribe it
yeah unity isn't going to serialize that (unless you make it a unityevent?) event
there's probably a better way to do what you're trying to accomplish that doesn't rely on that
does this need to happen at editor time? I guess I would just populate the meshes with whatever they need at runtime
if there are a lot of potential options they could ahve
both
Im making something similar to tilemaps
user should be able to make map with editor and during runtime
well i would probably look into how #βοΈβeditor-extensions work, since that's basically what you want here
then you can couple it to unity instead of to your scene and scene objects so that your events or whatever you're doing persist
ok, Will do
it will be hard to do it via events, since that will get nuked on all domain reloads
might have to be a editor scripting type thing where it queries for all the things it applies to and applies it
spawnInfos[i].OnRemove += () => { Destroy(gameObject); };
is there a reason why i cant assign this action?
: Cannot modify the return value of 'List<SpawnInfo>.this[int]' because it is not a variable
hmm looks like it worked after i made one inside the for int loop
indexer is method, so
spawnInfos.Get(i).OnRemove+=
also notice delegate is immutable as string
it's a struct so its not possible
spawnInfo.OnRemove += () => { Destroy(gameObject); };```
This worked
I am trying to use Array.IndexOf(instantiatedGameObject) to get the index of itbut the array itself was made inside the editor with prefabs.
IndexOf() is returning me -1 which means it can't find the gameObject in the array. This seems to be because the reference to the instantiated gameObect is not the same as the prefab itself inside the array. Not sure what to do
The picture shows the current values of things and the lists I am accessing
The gameObject is BallistaTowerLv1(Clone) and the list has the original BallistaTowerLv1 prefab.
My main question: How can I get the index of the BallistaTowerLv1(Clone)
They are not related. Maintain some sort of data that would indicate what it was spawned from, an ID on both perhaps.
I see. Was trying to get around that but I guess I will look more into this approach
hey, i have a place in my multiplayer game where when you go there another scene loads additively normally when there are more than 1 player and someone goes there the new scene only loads for the player that entered that area.
but if the host enters the area before the others join. when they join the scene loads for everyone that joins after the host entered the area.
how do i fix that ?
idk i started getting errors all of a sudden
didnt even change the code, just opened up unity and so many errors
you probably have a duplicate script
any clue how i can fix that glitchy transition
For a simple interaction/melee system would you recommend putting a collider on the swinging weapon/item, or have a box collider / physics cast in front of the character? I'm using the latter now, but my code is becoming quite messy. I think both solutions will end up with situations where it looks like you should have hit something but you didn't or you did but it looks like it shouldn't so I'm mostly concerned with minimizing code and making use of standard unity features.
It does look "of" but it's hard to tell whats happenning (to me), open up your character animator state machine, put in a scaled time=0.2 in editor/time settings and observe what states and states transitions are happening. This helped me debug stuff in the past. Maybe you'll see what's wrong (like a state is playing twice, or something like that)
well i only have 1 playermovement
screenshot all the errors
this is a code relation channel
my bad
is there a way to get the script of the built in nodes in visual scripting ?
i would like to understand how they make coroutine nodes
#763499475641172029 Should probably ask in the appropriate discord server - there's a special server explicitly for Visual Scripting.
guys i have a question
RaycastHit2D groundInfo4 = Physics2D.Raycast(transform.position, Vector2.down, 5f);
instead of down i want it at a 45* angle
i got it working
nvm
how to get final velocity from a projectile after penetrating an armor plate?
well, can't really expect us to work out the math for you if that's what you're asking and honestly quite ambiguous.
like, give us a little more information as are you using rigidbodies and setting density onto this object?
I created a post on the forum for a problem with QueryLobbyAsync, anyone that can help me? π
Hey there, I am wonder if I am able to control the windows OSK.exe postition from unity?
osk? virtual/screen keyboard?
on screen keyboard
i dont reckon there is any built-in solutions
public IEnumerator PositionOSKBottomLeft()
{
yield return new WaitForSeconds(3);
// Find the OSK window
IntPtr oskWnd = FindWindow("OSKMainClass", null);
if (oskWnd != IntPtr.Zero)
{
UnityEngine.Debug.Log("OSK window found.");
bool setPositionSuccess = SetWindowPos(oskWnd, HWND_TOPMOST, 0, Screen.height - 300, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW);
if (setPositionSuccess)
{
UnityEngine.Debug.LogError("OSK position set successfully.");
}
else
{
UnityEngine.Debug.LogError("Failed to set OSK position.");
}
}
else
{
UnityEngine.Debug.LogError("OSK window not found.");
}
yield return null;
}
you'd need to make your own
Use the OSK: On Screen Keyboard from Vancete.NET on your next project. Find this integration tool & more on the Unity Asset Store.
or use this asset
ah thanks so much, how did you know?
sorry that makes more sense now
i meant like how did you figure out but I don't think this will work
idk man i think you're lacking some english π read what i wrote again
I'm not I thought that was the integration for the actual microsoft integration, however I am looking to control the actual microsoft osk
So I asked how did you figure out how to solve this issue but we are thinking different things
have you tried to implement a .dll before?
!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.
A prof of mine showed a way for a singleton base class he uses. I just copied it and used it for my project.
However, I get a the following error from one of my singletons:
Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)
The following scene GameObjects were found:
Global Game Controller
Cant find solutions online, can someone tell me whats going on or whats the problem with the scripts?
Singleton: https://paste.ofcode.org/YVBvgcU8LV4kWZ9HCxCQSJ
Global Game Controller: https://paste.ofcode.org/WSUrLW9kQCMr2uHaWKQN23
CopySingleton looks weird to me but it's not instantiating anything, so is there anything else in the game which might be using Instance in a destroy method?
tbh I'm really confused why that exists too
hmm i dont think there is something like that. The weird thing is, i just click the play button in my game scene a couple of times. Most times the error doesnt appear, but every now and then it does.
You get this error/ warning when exiting play mode yeah?
too much duplicated code in that singleton too
I'm making a drawer for a serializable class, and running into some issues.
I've got the serialized property for the class, and in it is a reference to a scriptable object.
I'm trying to read a boolean off of that scriptable object, but doing this:
var statBlueprint = property.FindPropertyRelative("_statBlueprint");
var canDamage = statBlueprint.FindPropertyRelative("_canDamage");
Gives me null for canDamage. _canDamage does exist as a private serialized bool in the StatBlueprint class. Am I missing some in-between step to retrieve it?
statBlueprint is not null, so it's not that
Ah, wait, found what I actually needed to do:
StatBlueprint statBlueprint = property.FindPropertyRelative("_statBlueprint").objectReferenceValue as StatBlueprint;
And now I can read all the fields from the statblueprint in the class
what does lock do?
I'm trying to learn a bit more scripting and it looked like an interesting keyword to understand
It's for multithreading, allows you to lock access to something for a thread, so other threads can't mess with it.
the more fancy purple words I use, the more dopamine my brain receives
oh huh interesting
there seems to be a lot of multithreading stuff I do not understand
It's definitely an advanced topic when it comes to Unity games, most will never use them
shorthand for creating critical section
I was getting that error with my singleton too, except it wasn't listing ANY object at all. Just a blank line after The following scene GameObjects were found: which was not helpful
Though it looks like I fixed it at some point, as I'm not getting the issue anymore
better to leave alone till much further along, concurrency can cause lots of very strange bugs, and most unity code must run on the main thread anyways since very little of it is threadsafe
Everytime you even LOOK at Singleton<T>.instance it will create a new one, if one doesn't exist. I'd guess that something is doing that after you start closing the scene- it might be in OnDestroy, or it might be a response to a timer/event. IF this only occurs when the game is closing/quitting you can monitor this event, set a flag, and NOT create a new singleton instance once triggered. https://docs.unity3d.com/ScriptReference/Application-quitting.html
Hello I have run into a problem while working on my fishing top down game: I have a script for random generating prefabs of gameobjects of trees, rocks and mainly LAKES, where I have attached a script for triggering my fishing minigame (image). This script contains references to other game objects (interact window, timer etc.). Is there a way on how to "instantiate" (dont know how to use this word properly :D, so basically just fill) those references everytime the prefab of each lake spawns? I would appreciate any help.
exactly, sry for the late answer
lucky you, glad you got it fixed!
sry but what do you mean by setting a flag? And how do I monitor that? I searched for instance calls in the project but there seem to be non in ondestroy etc. Shall I just copy the code from the provided link?
I always just ignore them
true but I observed a couple of times where it then did not instantiate the go correctly on the next start. There then was an object with the same name without any components
that error has since been gone tho
how difficult is implementing steering behaviours for AI pathfinding 
like this where you have different weights for which direction the AI might want to go
by setting a f;lag I mean, create a static bool member say isQuitting in your singleton- default value is false. You can add a listener to that event I posted, such that when triggered, it will set that bool to true. Lastly, inside your instance getter use an IF to check that bool, and if true, abort creation.
NOTE: if this problem is occuring whe you say.. change scenes- my suggestion wont help. only good for quitting.
kedshfeiskd you game looks so gooood
mine doesn't
Here's mine, if you need one for comparison
https://pastebin.com/ribv0fhn
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
thats a good one
the problem happens when quitting the application and thanks for the help, I'll try refacturing the code :)
Hi. I have created my first unity protect. I don't have lot of knowledge in unity but I know C#. How can I split the camera into two parts and assign a different background color to each part.
There's probably another way to do what you're trying to do. Can you provide a visual of what you want it to look like?
I have set the backgroun color of the camera to blue but I want to split the camera horizontally into two parts each part with his own custom bg
I don't know if I have to create and script that implements the feature or in the other hand there is a way to do that without using c#
Why? Is each section for a different player? Or it's a different play space?
Its for a single player but I want to set it like that as there are like two teams blue and red but the UI will be only used by one player.
The hardest part is actually getting the data for what is a valid path. You could just use unitys navmesh for this. The pathfinding algorithms are already invented, you just need to choose one.
If you're talking about doing this solely based on raycast (which is what your image looks like) then that isnt pathfinding because it's just going in the direction of least resistance and hoping there isnt some giant wall it isnt aware of
You're far better off just putting a flat plane there with the right colors. Trying to split this up into 2 cameras is going to be far too much of a headache
Or a large sprite that's just a single colour
and where I find a flat plane. Sorry but as I said I don't know so much about unity. I am testing and then I will start reading the guide and docs. It could be a canvas in component > layout ?
Is this a 3D game or a 2D game?
2d
Create a square PNG in the art package of your choice (i.e. GIMP) of the right colour. Dump that into your scene as a sprite and stretch it to the right size as your background.
so I have to create a PNG which will be my background? and then add it as an script an resize it with the dimensions of the camera?
Do you want it to move around with your camera? Or is your camera just going to be locked in position the whole time?
there was a thing idk whats its called but like certain type of code. My teacher suggested for us to look into it as it would help us with a problem someone had, where basically they wanted to close whatever UI menu was open if another one gets opened, anyone knows what im talking about here?
It's a fixed view where the user only have to click buttons etc.. so there is nothing that has to be moved
Then you're just placing the sprite in the scene and adjusting the transform on the object to position and scale it. No scripting involved.
The scene is the level, you're placing an object in the level to act as your background that the camera is looking at
Then whatever other sprites you have will just be above that background sprite
Okey. Thanks.
Or, if you're doing everything in UI only, with no sprites, then you'd place Images in your Canvas as the background, and stretch those to fill the canvas and colour them
I want to learn how to use unity and code different things but Iβm unsure how to learn the code that is used for making games
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I would like to add two sprites but they will be only static so I think the static background is suitable
I have a game object that appear on the "scene" but not in the "game" tab, it uses a code to move with the mouse but does not show on the game render, do someone know why ?
It's probably just too close to the camera
Is it a 2D game? If yes, just set worldPos.z to zero
IIRC ScreenToWorldPoint gives you a position on the camera's near clip plane
what would be a good workaround to this issue, "size of the vertical scrollbar reverts back to 0.61 when trying to adjust the value slider"
I am dealing with this problem where i have multipple buttons
inside scroll view and i cannot see all of them
that issue is about the scrollbar itself
it sounds like your problem is about the contents of the scroll rect
yes, and i ask here because maybe there is a programmatic solusion
put a ContentSizeFitter onto the "Content" object
Also put a VerticalLayoutGroup onto the "Content" object. Check both "Control child size" boxes and uncheck "force expand"
You will now need to put a layout group onto every object that has children.
- Content <-- ContentSizeFitter, VerticalLayoutGroup
- ButtonParent <-- VerticalLayoutGroup
- Text
- ButtParent <-- VerticalLayoutGroup
- Image <-- VerticalLayoutGroup
- Text
- Image <-- VerticalLayoutGroup
- ButtonParent <-- VerticalLayoutGroup
e.g.
All of them should be set to control child size.
This is a #π²βui-ux problem, so if you have further questions, ask them in there
(i'm getting back to work and won't be around for a bit)
ok appologies, and thank
I am trying to make the bullet trail for the weapon disappear after the certain time has passed
the idea is to simulate what would be a gameobject projectile while I am just using raycasts
I am trying multiple approachs but cant seem to find one that works
why dont you just use a linerenderer
it is a linerenderer
it is a gameobject with a line renderer
and nothing else
so, what's the exact problem? You can set the time which each segment expires.
can I dynamically adjust it tho?
uh, it may use keypoints
cause the problem I have is that I want it to disappear depending on how long it would have taken a gameobject to hit whatever was hit
and then run all the logic after that time has passed
or should I instead have no bullet trail and just show a muzzle flash and an effect where the bullet hit?
I think that's a better idea and I am just making it harder for myself
https://docs.unity3d.com/Manual/class-TrailRenderer.html
Sorry, I meant trail render, not line
Has a time property
I am doing a canvas but I can't reduce the width or the height and I can't move it through the screen
Not sure if there is a particular word for it, sounds like your describing just updating a reference, or possibly a event bus could also handle something like that, or possibly a state machine, though those approaches are usually a bit more involved than your description, it sounds like your more-or-less asking about something like this?
public class SomeUI : Mono
{
GameObject opened; //keep a reference to what is opened
public void OpenAnother(GameObject ui)
{
//should probably do a null-check incase nothing is opened
opened?.SetActive(false); //hide the previous window
opened = ui;
opened.SetActive(true); //show another window
}
}
In that example, something would call OpenAnother passing the UI object that should be displayed, causing the current one to close, get updated and show the one passed instead, though im not 100% certain if this is what you were trying to describe
The canvas has 3 modes, by default it is locked to the screen space overlay, meaning it will render above everything and cannot be adjusted through the transform, instead it uses a Canvas Scaler to adjust itself based on the screen its displayed on: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UICanvas.html
If you want to be able to change the size of the canvas itself, you may want to try one of the other 2 modes, however that also means it wont properly overlay and fit the screen, so its good for in-world UI but not UI you might want always on screen
I'm trying to resize it because I want it to fit with the camera
alr thanks
Also I'm trying to change the button text of a button in that canvas but there is nothing in the inspector that might be consider to change the button's text
Ah, instead you might want to try the Canvas Scaler instead: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-CanvasScaler.html - there is a mode to have the canvas match the width or height (or attempt both), based on the screen resolution, which the Game window can preview for you (normally the area that says "Free Aspect" can be changed to specific resolutions)
Apparently my question should be asked here instead of #π»βcode-beginner -
Hi everyone! I need help with a terrain generation script that I tried modifying to work multi-threaded using Burst and NativeArrays/Lists. The game I'm working on is meant to feature a minecraft-esque terrain and I had it working single-threaded and using a LOD system that just lowers the resolution of the voxels the further away you are from them on orders of magnitutes of 2. This was all working on a single thread but was obviously very laggy when you moved between chunks because all the processing was happening on the main thread. I've programmed what I believe should be the multi-threaded equivalent of the previous code I had written but now nothing renders and additionally I've got an error along the lines of "Leak Detected: Persistent Allocates 1 individual allocations." which I'm not entirely sure how to fix because I need this array to stay persistent
The text would be a child of the button object, youd have to select that child object to change the text through the inspector (assuming you dont want to do this at runtime/through script)
okey thanks I'll try it
ah I didn't see it in the hierarchy
is there a way to tell which monobehavior this was? as in a string name or something
hey, quick question, can this be used for 2d games? they seem designed mostly for 3d
prob not , seems it doesn't have the .meta
I don't think that's the case because this seems to happen when scripts are deleted after they've been attached no?
I guess just gotta dig into the yaml
I don't think there's a 2D variation, but I don't see why it wouldn't work
ok, gonna give it a shot
That's probably your best bet
well yeah thats if you delete the file without deleting it from the object you're gonna see that
yeah exactly, question was figuring out which file that was, but looks like I just have to redo this because it's related to UI Toolkit being updated between 2020 and 2021
Did the meta file tell you what component used to be there?
oh hmm I only checked the .prefab yaml file but that only had guids
so I ended up removing them and yolo guessing based on the script and kinda got it working π
Thoughts:
When a player turns sound effects volume to 0 it is inefficient to keep audio sources enabled in the scene.
have you actually profiled to notice any benefits?
This is not an issue I am currently facing. I just wanted to open a dialogue.
I get that, and asked if it was speculative or legit
Well, I am speculating that it would be more efficient to disable all sound effect audiosources.
Someone else might subscribe to another school of thought. I can already hear someone saying it's a micro optimization.
How do you update navmeshsurface via script?
reference it
call bake
done