#archived-code-general
1 messages · Page 280 of 1
So running in Update, I run this:
in CompleteProjectileHits(), literally it stards with handle.complete(), and normally place it in Late Update. I shoved it in there and no errors, so it runs in the update.
I hope that makes sense. Thank you in advance any advice and for your time!
i’d recommend you put that chunk of code in one of those paste sites in #854851968446365696
got it! Doing it! sorry!
Yea I got it but I didn't do waypoints. I simply made collision so it would update the z axis
Hmm... According to docs, tempjob allocation lives for up to 4 frames, so that shouldn't be a problem🤔
exactly! I got rid of any logic on seeing if I needed to run it, in case I was messing up, but same thing.
So I'm sure I'm just doing something wrong? It seems OK to me but what do I know lol
Can you share the exactll error?
for context, points to line 131 which is starting the for loop. handle.Complete(); for(int i = 0; i < raycastCommands.Count(); i++)
the line immediately after I complete it. I dispose after the loop
I think the error implies that there's double deallocation going on. Maybe that code runs again after the arrays were already disposed?
Looks like it's the Count call that's the issue
I was running it when no job was scheduled
Ah you figured it out
and I thought my logic was good to be like "hey do this if I have a job"
but no
for I am dumb
THANK YOU @cosmic rain
I just added a bool for when I scheduled the job and checked for it, and reset it after I cleared it. I... don't know what I was doing before but it was wrong.
sigh
not sure why they let me drive a car
yet here I am
thank you all, much appreciated!!
Hope you all have a good night
Well, we all make mistakes
My wife reminds me daily, yes lol
!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.
Hey everyone, so in my ball throwing game, i'm trying to make it so that when my player releases space,, the ball releases from the player's hand and scores a point. I'm having an issue with releasing the ball from the player's hand. Here is my ball holding and throwing script: https://hastebin.com/share/sayujacadi.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
do you have multiple balls on scene
btw sounds code beginner
click left button->hold down space bar->release space bar->release left button, then the ball wont being thrown?
Nope
The ball is released tho
I think the if section stops being true once I release the space button and the "isHoldingBall" becomes false
But I'm not sure how to do it any other way
you have 6 if blocks here, which one?
The last one on "ThrowBall"
HoldBall.isHolding becomes false once you release the left button or release the space bar, what is the problem?
I think that since the ballRb.AddForce does not work because isHoldingBall becomes false
Or is that not how if commands work 😅
Either way, do you have any idea on how to make it so that the ball will have the force added onto it?
The reason I had the ball release from the player, was so that it wouldn't stay in that spot
oh i see the problem, try apply impulse force
So that, didn't fix it...
It still releases the ball, and doesn't add the force
It might be a seperate issue, I tried this and it didn't add any force anyways
normalize the direction at first, then try to multiply it with a large value eg 100000 to see if the ball moves
i think the isholding ball is not the cause
I'll do that in a second, but do you think it has to do with the ballForceDirection?
yes
Like this?
yes
Unfortunately, that did not fix it
btw you dont need to declare everything to be class fields
post the rigidbody setting
Sorry, I don't know what you mean by declaring everything with a class field
mistypo
Was reading someone's dependency injection utility and they said it supports monobehaviours and components. What is a https://docs.unity3d.com/ScriptReference/Component.html and how would you use it? Any monobehaviour script you write you then interact with GetComponent or AddComponent, so how do you interact with an actual Component classes, is there some common real world use case for them or is it just an implementation detail of monobehaviours?
try disable the part that moving ball transform
// Calculate the desired position based on camera's forward direction
Vector3 targetPosition = mainCamera.transform.position + mainCamera.transform.forward * distance + Vector3.up * height;
// Set the position of the object
transform.position = targetPosition;
// Make the object look at the camera
transform.LookAt(mainCamera.transform);
```though i think it should not make any effect after release the space bar
That whole part?
oh wait, is this script on your ball?
Yup
then```cs
ball = GameObject.FindWithTag("Ball");
Oh lol
I think I was planning to put it on the player and switched halfway through
OH WAIT
So I'm planning to have multiple balls in the fuuture
I think that was in plan for that
But I know that'll require some other stuff too
I just want it to work in this way first so I have a baseline on what I need to do
Anyways, did u find any solutions to the ball having the force applied to it?
not moving the ball transform
but after moving it the ball should still move since it velocity is not zero
Sorry, but I don't understand.
comment out the code i posted
This one?
Or this?
the part that moving the ball transform
So I did these 2 things
And it still does not fix it
Do you have any suggestions on changing the ballForceDirection (if that's the issue)
I tried it with and without commenting the code, but it did not fix the issue.
apply a constant force
is there any other script modify the ball transform?
- How would I do that
- No
dir.normalized*10000, dont take heldtime into account
That didn't work either...
Oh
Could it be because it is grabbing it's own transform.position
In that case, should I put the script on the player?
Just to clarify, is it grabbing the "ball" position twice because it is attached to the ball?
the ThrowBall is not in player but in the ball?
then the direction vector always zero
Yup
i think it is on player at first
I have moved it onto the player now, and it fixed the issue
However
Whenever the ball moves, it moves in a downward direction
*forwards and downwards
Nvm, the main issue is resolved and tweaking should fix these minor things
Thank you for your time!
is there supposed to be a difference when assigning sprites to a spriteRenderer vs a UI image? I'm in a situation where I have to create a sprite from an SVG, but the sprite only seems to be visible on spriteRenderers and not UI images
void Start()
{
List<VectorUtils.Geometry> geometries = GetGeometries();
Sprite spriteFromSVG = VectorUtils.BuildSprite(geometries, pixelsPerUnit, VectorUtils.Alignment.Center, Vector2.zero, 128, flipYAxis);
//This doesn't work
image.sprite = spriteFromSVG;
//This works
spriteRenderer.sprite = spriteFromSVG;
//These both work
image.sprite = spriteInspector;
spriteRenderer.sprite = spriteInspector;
}
private List<VectorUtils.Geometry> GetGeometries()
{
using var textReader = new StringReader(svg);
var sceneInfo = SVGParser.ImportSVG(textReader);
return VectorUtils.TessellateScene(sceneInfo.Scene, new VectorUtils.TessellationOptions
{
StepDistance = 10,
SamplingStepSize = 100,
MaxCordDeviation = 0.5f,
MaxTanAngleDeviation = 0.1f
});
}
weirdly enough, assigning a sprite from the inspector seems to work just fine for both
settings on UI Image
there is clearly a sprite (when I click on source image), but it's nowhere to be seen
I also have the option of converting a dataURL (base 64) string to a sprite, but I had no luck getting that to work either
I already have the code, I just dont know how to make something bigger or smaller using the same object when interacting (without hiding or setting to active), or should I just use set active?
functions are confusing 
How do I apply uniform scale whenever scale gizmo is used? For example if someone drags any of the x, y, z handles I want to set the scale to Vector3.one * <scaled axis>
ideally I would like to disallow even using the scale gizmos for each axis separately for such objects... but I doubt I can do that
Is there some smarter way than keeping track of previousScale and comparing each component separately in OnDrawGizmos/OnGui or something?
I figured out the dataURL conversion wasn't working because the mime type is gif, and that doesn't work. I had to find a new library that can encode png and jpeg
but the whole svg thing is still a mystery
Any tips of how to get more "organic" following behaviour? Right now each goober just attempts to path straight to its designated point in the formation. The formation itself rotates towards the player and follows them if they get too far away.
- a more organic shape for the formation would probably help (and i'd space the dudes out more with some variance since they are unnaturally stacked)
- if you give them some movement animation (bob up and down maybe), that would add some organic noise to the mass
- you could also give them different/varying speeds and let them push each other out of the way so that they don't feel so monolithic
just some random ideas...might be worth looking at what the pikmin games do or how schools of fish move, depending on what behavior you are looking for
I'll try some offsets on their position. I 100% think I'm losing a lot of charm due to the lack of animations.
I kinda want/need them to be this crunched though.
I'd like... 100 of them >_>
and this is only 20
if you can put jiggle bones on the antennae that would add a lot
that's the plan
Hey everyone, do you know this pack? I have a small issue with the ,,Fixed joystick" script. I want to change something in the code (made something public) but the code looks empty (in the inspector everything looks normal). If you guys have that script it will be awesome if you will send that.
fix what?
basically the object ref not set to obj error occurs becuae of the lm line
the ground info 1 bit is the thing causing the error
you only check groundinfo but you didnt check groundinfo1
How to check if certain object or tilemap is under mouse?
Or check if certain object with tag
please...
Hello!!
I have a simple panel for entering text and sending a message (in the first video)
there is such a problem
I have a script that controls the position of the panel depending on the size of the keyboard using the OnSelect and OnDeselect events
due to the animation of the panel shifting, when you try to click on the send message button, it does not work
How can I make it so that I can:
- click on the send message button
- do not move the panels when you click on the send button or gift button
Script that move my panel up and down
public class KeyboardHandler : MonoBehaviour
{
[SerializeField] private InputFieldView inputField;
[SerializeField] private CanvasScaler canvasScaler;
[SerializeField] private RectTransform moveRoot;
[SerializeField] private float moveUiSpeed;
[SerializeField] private float testHeight;
private Tween _moveDownTween;
private bool _keyboardIsActive;
private void Awake()
{
inputField.OnSelect.Subscribe(OnKeyboardActivated);
inputField.OnDeselect.Subscribe(OnKeyboardDeactivated);
}
private void Update()
{
if (_keyboardIsActive)
{
var rate = canvasScaler.referenceResolution.y / Screen.height;
#if UNITY_EDITOR
var height = testHeight * rate;
#else
var height = SoftwareKeyboardArea.GetHeight(true) * rate;
#endif
var anchoredPosition = moveRoot.anchoredPosition;
var targetPosition = new Vector2(anchoredPosition.x, height);
moveRoot.anchoredPosition =
Vector2.Lerp(anchoredPosition, targetPosition, Time.deltaTime * moveUiSpeed);
}
}
private void OnKeyboardActivated()
{
_keyboardIsActive = true;
_moveDownTween?.Kill();
}
private void OnKeyboardDeactivated()
{
_keyboardIsActive = false;
_moveDownTween?.Kill();
_moveDownTween = moveRoot.DOAnchorPos(Vector2.zero, 0.1f);
}
}
my behaviour
desired behavior
this is my send button
I try to add simple filtration, that check current selected object and if this object is my Send Clickable view Select input field again, but in this case my currentSelectedGameObject is always "input_field"
If I check currentSelectedGameObject when Click to my button I have null in EventSystem.current field
maybe just focus the field again after you hit submit so that they keyboard doesn't close
I have no mobile experience, but I think maybe you can set the button so it can't be selected
You could also try making the button something that isn't a Selectable (for example an Image) and add a custom IPointerClickHandler on it
That way it will never be the currectSelectedGameObject
is there a limit of iteration inside a while loop ?
i would like to run a coroutine that does stuff in a while true loop for the whole game
no
As long as you yield in the loop, your game won't freeze. Always make sure all code paths in a loop hit a yield
Else you'll freeze your game
How can I change the width and height of an object in RectTransform Component in script?
Alter its .sizeDelta vector
What do you think about having 1 point of update, lateupdate, fixedupdate in the project, is it worth it?
hiii
As in having one sort of master "clock" script that reads the unity messages and passes it to everything else? It's a lot of work but it actually comes with tons of benefits, especially if you want to add in any sort of slowdown or frame by frame mechanics into the game
i need some helps in writing a shader for a 2d pixel art style water it would be glad if someone direct me to the relevant sources!
Also makes pausing pretty trivial to do which is normally a huge pain
i am new to unity but experienced in other game engines but never wrote shaders before
just need a direction where i can start
like this
I have an interface for special cases, with a function that does something something, and then returns true/false to let the function that invoked it know if it should also continue with non-special case code.
This feels… inelegant. Am I doing something dumb?
ou i see thank you
https://ameye.dev/notes/stylized-water-shader/
Or just random blog posts that go into more detail
blog is better
Show some code, am curious to see... buuut all in all it seems fine to me 🙂
That's more 3D though, but some similar concepts for 2D
///<summary>Update preview based on the state of building input.</summary>
public void UpdatePreview(BuildingCreator.BuilderInputState inputState) {
UndoOldPreview(inputState.lastGridPos, inputState.selectedObj, inputState.buildModeType);
if (inputState.selectedObj.customDrawLogic != null
&& !inputState.selectedObj.customDrawLogic.DrawPreview(inputState)) return;
switch (inputState.buildModeType) {
case BuildModeIndex.Normal: DrawPreviewDraw(inputState.selectedObj, inputState.currentGridPos); break;
...
...```
Yes, that'd be the way to do it. Including the deltaTime as a parameter was a good call too
Are there people who have implemented this in practice or know if it works well or not?
in my case, it isn't exactly obvious if true vs false means we should continue
yep
call it TryDrawPreview then 😛
so does true mean it successfully drew a preview, and we’re done, or true that we need to continue to normally draw preview as well?
same as all Try things - true on success of the operation
it doesn't know what the outside is using the result for
ok… but the thing is that this is an additive process. I may do something (or not) independently of whether or not I should also do the rest of the process
I see... 🤔
TryDrawPreview false means it did not draw, but what if it did draw but needs me to go on as well
it’s partially a naming issue
i could make an out param, but idk if that exactly fixes the issue
you could maybe return an enum instead of bool
then it's more explicit about the meaning of the value
I'm not a big fan of out params... but it does seem like a reasonable approach
i’m not either. this feels janky, but it is at least clear what I want to convey
Hi guys, need some help. I'm trying to open a generic field to the inspector but I'm receiving an error:
"The field Dealer<System.Single>.affector has the [SerializeReference] attribute applied, but is of type Affector<System.Single>, which is a generic instance type. This is not supported. You must create a non-generic subclass of your generic instance type and use that as the field type instead."
The code it's pointing to is below:
public abstract class Dealer<T> : MonoBehaviour
{
// --- snip ---
>>> [SerializeReference] public Affector<T> affector;
// --- snip ---
}
I'm concerned because the field's type is based on the class's defined type, so I cannot define a concrete type like the warning is suggesting. Am I SOL on this solution?
Unity version: LTS 2022.3.20f
SerializeReference doesn't handle generic types
yeah, just make a concrete type
perhaps it's fixed in 2023 though
if you have the option to use that (I don't see this limitation mentioned in the docs there)
I see, is there any other way to expose it it in the editor? if it helps the Affector<T> is a interface and I read this is one of the ways to expose it.
public interface Affector<T>
{
//---snippy---
}
I personally have:
FixedSpawnBase : Monobehaviour
FixedSpawnBase<T> : FixedSpawnBase
FixedSpawnSingle : FixedSpawnBase<TilePlacementInstance>
FixedSpawnLine : FixedSpawnBase<TilePlacementContiguous>...
Odin Inspector
TNRD serializable interfaces plugin on openUPM. But idk if it works with generics
but stop trying to serialize generics
(consider prefixing interface names with I: IAffector<T>)
Ah i get the meaning, but the error is coming from the original base file which is in itself a generic type and they (field and class) need to be of the same type so I'm not sure if that would work in this scenario
Ah right I'll get down on that, thanks
so, you can't just use newer version of Unity?
in general, if it is serialized, it should be a concrete type
it is a concrete type, Unity is just kinda stupid 😛
(well, they seem to have fixed it in 2023, so there's that)
assignment restrictions ._. I'll run it by the teacher if it can be done
ah sweet
either way, you should get the tnrd serializable interface plugin
it is good for serializing fields that are an interface
hey, you can use Pulni's Editor Tools if you wanna serialize interfaces and abstract classes and all that 😅
unknown dev is sus
but not the thing that you want, because technically it's still based on [SerializeReference]... it's more of a helper on top
Gonna test the 2023 ver, o7 I'll give the tools a try later too. Thanks guys!
also uses [SerializeReference] inside so can't handle generics of that type, but seems pretty cool otherwise 👍
I wouldn't expect it to handle generics tbh
well it is just a Unity limitation 🤷♂️ ... nowadays you can do [SerializeField] private MyClass<int> myVar; and it'll show just fine... but if you wanna do SerializeReference and gain the ability to serialize interfaces/abstract stuff - it doesn't work
Im using this code to take a screen capture of a specific region
it captures from the smaller camera
it works fine in the editor, but when i build my project the screenshots it returns are blank with the wrong resolution
So im guessing the camera is scaling weirdly during building or something like that
1 is in editor, 2 is in build
I dont really know how to fix it because I dont know how building affects things like this
yeah sadly on that point updating to 2023 got rid of the error but still didn't allow the field to show up on the inspector. Ended up moving around some inheritances instead and made it a base class instead of an interface reference. Good Code this is definitely not but anything to pass the class. Thanks again for the help!
That's weird... if the error was gone, the field should've been visible 🤔 I'll go download some new Unity and try it myself, am curious now 😄 (I use [SerializeReference] all the time... can't help it 😅 )
Hehe you're welcome to give it a shot. Maybe you'll catch something 2am brain missed
This is what I currently have if it helps at all
Unity Version: 2023.2.12f1
Generic.cs
public abstract class Generic<T> : MonoBehaviour
{
[SerializeReference] public IInterface<T> affector;
}
public interface IInterface<T>
{
}
Concrete.cs
public class Concrete : Generic<float>
{
}
put Concrete on a Gameobject and the field will not be shown
it makes sense for an enum that tells me the overall play mode to be a static variable, right?
eg. in overworld, in level, in main menu...
otherwise I think i'm struggling with singletons instancing in order or disappearing.
making it static fixes a lot of issues with initializing and closing, but i get an ominious feeling of doom
I'd say go for it until it's a problem 😛
main issue I've had with static things is when you wanna do a clean reset, you need to tell all the static places to lose their data
the main use case is to tell the main scene if we are in level editor mode or not. So clean reset isn't really a problem... probably
This one specifically doesn't seem like it'll be problematic, yeah
Problem with animation. My panel move when inputfield ondeselect and i cant click my send button
This works fine for me:
public abstract class GenericTest<T> : MonoBehaviour {
[SerializeReference] public IInterface<T> testRef = new Instance<T>();
}
public interface IInterface<T> { }
public class Instance<T> : IInterface<T> {
public T data;
}```
(having a class Concrete : GenericTest<float> like you)
I'm using the Spline Package so I can move things around in my scene along a path and I have looked at the documentation, but I can't seem to find what I'm looking for.
I would like to know the following
- Is there a way to tell if an object has fully completed a path over the Spline.?
- Is there a way to change the speed of an object while traveling over the spline?
- Is there a way to tell the object to stip following the Spline for a set period of time?
- If I want to have an object branch onto a linked Spline how do I tell the object if it should do so?
how can i edit the post procesisng volume intensity with a script ?
The volume itself doesn't have an intensity, but you can access one of the effects and modify that
volume.profile.GetSetting<T>().intensity = 42;
Where T is one of the post process effects settings class
is that the same as the weight, sorry i thought it was an intensity slider but its called weight
Ah no that's the weight of the volume component itself
That would be modifying its .weight property
ahaha now that im using the right name i actually found it, thank you
is there a better way to do this?
public void Method(int index)
{
index = (index + 1) % MyList.Count;
if (index == 0)
{
WrapCount++;
}
var thing = MyList[index];
}```
Your thing variable is not used. I see no reason for it . . .
yeah its just an example for now, I'm mainly asking about the counting how many times it wraps around the index
This doesn't count that though, does it? It just adds 1 to the WrapCount if it wraps at least once
Unless you're repeatedly calling it for each index
Oh hold on
@random oak you could keep the raw index, use int div to know the wraps count and use modulo when accessing the list
yeah maybe I can keep track of both index, was just wondering if this is better than what I have now
@random oak What 2 indices?
WrapCount can be determined dynamically by index / yourListCount
if you don't use modulo on your index
oh was thinking one that wraps and the other index that doesn't
With your current code, the index isn't kept. The one you pass is incremented and wrapped if needed, but that's pretty much it. You probably want to do it on a field instead, and modify the method so it doesn't take any parameters
itemSlots[col][row].(MainFrogController)Item.FrogController
Is there a way to cast Item to something and get a variable in the same line? Or do I really need to put the casted Item into a variable and then use the getters?
yeah that's good idea, I think I will do it that way
Local variables are discarded when execution exits the method, and the fact that int is a value type, you're working on a copy, whatever variable you passed to the method won't be modified at all
Like with math, use parentheses to prioritize operations:
((MainFrogController)itemSlots[col][row].Item).FrogController
Note that this will throw an exception if the cast fails. If it's possible to have anything else than a MainFrogController in thata property, consider type-checking before casting it, or using is to both type-check and cast at once
var item = ...;
if (item is MainFrogController ctl)
// use 'ctl' variable which is 'item' cast to 'MainFrogController'
parentheses are always great
until you get into a dumbass twitter argument where people don’t remember how math works without them
one of the worst ones was most people saying
-1^2 = 1, which is just wrong
-(1^2) 🙂
in all fairness, sometimes it's better to be explicit with the parentheses just so that people don't have to remember the order of operators and no random mistakes happen
- ^ 1 2
the -1^2 may confuse people, because ^ is somewhat uncommon to deal with
(and of course we're ignoring the fact that in C# that's a bitwise xor operator and not a pow operator 😄 and I have no idea what is its order relative to the unary - 😄 )
If I remember correctly it's one of the lowest, below == so it's weird at first when you do a ^ b == 42 and it complains
Hello everybody !
I'm currently making a shooting system and i have an issue, my bullet get out of my muzzle as wanted but it is shooting not at the center of the screen, i have my gun deported of my camera and i wan't to shot my bullet where the center of my camera is.
Do you know how could i improve this script ? :
//direction from the weapon muzzle to the weaponpoint (where the player is aiming)
Vector3 direction = (weaponPoint.transform.position - this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position).normalized;
bullet.GetComponent<Rigidbody>().AddForce(direction * weaponSpeedBalisitic);
bullet.AddComponent<BulletScript>();```
guys why can't I git push files over 100MB? I read online that github desktop has lfs and should be able to do that?
Hey, if somebody could help me with my FPS-Rotating that would be great.
This is my first time really programming a charactercontroller myself and not just copying a tutorial or using a free asset.
I wanted to do it myself.
void CameraPositionSync()
{
Vector3 offset = head.forward * headZOffset;
maincamera.position = head.position + offset;
}
void HandleLook()
{
//Rotate the player left and right based on the look input
float XRotation = inputHandler.LookInput.x * lookSpeed;
transform.Rotate(0, XRotation, 0);
verticalLookRotation -= inputHandler.LookInput.y * lookSpeed;
verticalLookRotation = Mathf.Clamp(verticalLookRotation, -UpDownRange, UpDownRange);
maincamera.transform.localRotation = Quaternion.Euler(verticalLookRotation, 0, 0);
}
I have some problems explaining what I am doing (as english is my second language 😅 Sorry)
So here is a small video of my FPS controller problems.
transform.Rotate(0, XRotation, 0) *;
???
Sorry, that musst have slipped in while copying the code 😅
Where are these being called from? These should be ran on each Update.
I need help, I am coding a bow that just launches an arrow then you click but I cant get it to launch in the direction I am facing, but no matter where you turn it only launches in one direction, I have an arrow placeholder which is just a placeholder for the arrow to spawn at when instantiated and the arrow prefab. I am using AddForce to launch the arrow and I have it on Impuse. I used Vector3.forward for the direction but it is going forward globally rather than locally. Can anyone help?
Arrow placeholder code
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
public class ArrowController : MonoBehaviour
{
public GameObject arrowPrefab;
public GameObject bow;
public GameObject Holder;
public GameObject player;
public Vector3 startPos;
public Quaternion startRot;
public bool canLaunch;
// Start is called before the first frame update
void Start()
{
canLaunch = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (canLaunch)
{
Launch();
StartCoroutine(LaunchDelay());
}
}
startPos = transform.position;
startRot = player.transform.rotation;
}
IEnumerator LaunchDelay()
{
canLaunch = false;
yield return new WaitForSeconds(1.5f);
canLaunch = true;
}
public void Launch()
{
Instantiate(arrowPrefab, startPos, startRot);
}
}
Arrow prefab code
using System.Collections.Generic;
using UnityEngine;
public class ArrowPrefab : MonoBehaviour
{
public Rigidbody rb;
public float shootPower;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.forward * Time.deltaTime * shootPower, ForceMode.Impulse);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
rb.velocity = Vector3.zero;
//Destroy(gameObject);
}
}```
If the script is attached to the player replace Vector3.forward with transform.forward
Otherwise same thing but reference the player, so player.transform.forward
Oh wow thanks so much
Np
Is there a way that the character can be seen though the wall depending on layer?
camera tricks or rendering order tricks or stencil tricks
I tired the camera trick though not sure why it never worked
let me try that
Hey not sure if the right channel but Im trying to grow a spriteshape over time. I have a script that basically does what I want with the exception of tangents. I set points to continuous tangent mode in the script but it doesn't seem to really take effect correctly.
If I go to the scene view and switch the point to linear, then back to continuous, it takes effect as I would expect. Is the missing step here that I need to calculate my own tangent points and set them in the script as well? Is there any way I can get the auto tangents the editor seems able to apply?
I got a decent enough result using those tangent functions and just estimating good tangents based on a rough heuristic.
How was this hyperlink done?
Debug.Log supports rich text (bold, italic, colors, etc.) so you can use a HTML link tag in it. <a href="...">text</a>
Thank you, works
is there a fixedUpdated version of getButtonDown?
No
need to know if a player presses a button while in a trigger collider but getButtonDown doesn't work
You should never use single frame input in fixedupdate
what should I use instead?
When they enter a trigger, set a bool true, on exit, set it false.
Check for input and the state of that bool in update
thanks
have u guys use Physics.SphereCast with both index layermask and float maxdistance as parameter ?
they didnt work
it also happen to capsulecast
you should be using a layermask
float moveDistance = speed * Time.deltaTime;
bool hitted;
Ray ray = new Ray(bottomPos, moveDir);
if (useCapsuleCast){
hitted = Physics.CapsuleCast(bottomPos, topPos, radius, moveDir, moveDistance, hitLayerIndex);
}
else{
hitted = Physics.SphereCast(ray, radius, out RaycastHit hitInfo, moveDistance, hitLayerIndex);
}
if (hitted){
Debug.Log("hitted");
}
}``` like this
the layer index you see on the game object is not the same as layermask
i know. it set it correctly
layermask = index in editor + 1
bzzzt

what is the number because it would not be 2 digits lo
oh, so it is wrong knowledge
i read it somewhere
change to layermask worked
thanks a lot
That sounds like it's mixing this up with Random.Range (which you need to add 1 to for ints, because the int overload is max exclusive), and indexing in arrays (which you need to sometimes SUBTRACT one from, because array indexes start at 0)
In case you didn't look at those links, think of layermasks as just a series of flags, in a 32 option long list
Your instance also works on my side o-o Probs messed up something along the way, I'll take a second look at it when I have the time. Glad to know the concept works at least, thanks a ton again for the help!
Happy to halp! 😛
help my first proj i been stuck on 2d map noise procedural generation with partial map loading
i cant find any yt guide for this, whats the approach to combine these two
I can't make a fullbody fps controller with Unity 😦 can you suggest a tutorial for this?
What part are you struggling with, and what have you tried already? A fullbody FPS controller is just a regular FPS controller (so any tutorial on making a FPS controller should help), only adding a rigged model and aligning the camera to the head of that model, I would suggest making sure the model you use has the head separated from the rest of the body so the head can be disabled or set to a layer not rendered by the camera to avoid clipping
I actually use the Unity Rig system and every time I have difficulty in one part.
Every time I try, I encounter a different problem and I guess there is no tutorial
https://youtu.be/yexW1VBgFbA?si=niKD9ggeJVsldE78 I wanna do like this.
I found this https://matthew-isidore.ovh/full-body-fps-controller-part-1-base-character-controller/ maybe this will be useful for me.
Sure, try that tutorial and see if it helps you, there should be tutorials on how to use the Rigging system package, though if you cant find anything on google, then describing your specific problem, setup, and desired goal can help, that video to me, looks like they may be using regular FPS arms and rendering a full body without the head and arms separately, or their animations are very well done, as posing, and aiming with a full body character can be difficult without the arms being a separate thing from my experience
Is there some magic way to create a GameObject without having to reference copy another gameobject using Instantiate, but instead by simply creating an empty shell GameObject? The same kind you get when you create a new GameObject in hierarchy. I tried looking up "unity Instantiate without gameobject" but no luck...
I'm doing this because I find it a waste to go out of my way to get some empty prefab object's reference and instantiate like that, although i'll just resort to that method if needed
use new GameObject()
I'll try that, thanks! new gameobject() seems weird to use..
why? GameObject is a C# class like any other
that's really interesting, I didn't expect gameobjects to be so close
I suppose it's counter intuitive as you cannot use new() for Monobehaviours
MonoBehaviour's an abstract sort of class right?
those types can't be created without an inheritor class, which makes sense
well, it's a bit more complicated than that because you cannot new() anything that inherits from MonoBehaviour either
nope, only AddComponent
maybe because the rest of the unity project has to know you added it? maybe the object it should be attached to for example
also Mono's span Managed and Unmanaged memory so there is a lot of stuff going on behind the scenes
so the unity project has to manage the memory of the monobehaviour too
what sort of code prohibits newing a mono? maybe just explicit unity code?
exactly
now that was interesting
I have a problem with choosing the right animation. Currently, the from any state, we can choose to jump or walk, but using a bool for walking makes it overwrite the jump when player is jump and moving. Is there anyway to set priority for the animations? thanks
nvm Imma create my own Animator Manager with Priority Queue for that
<@&502884371011731486> Spam
I have a super hard time working with unity's spline package. It doesn't seem to use any of the standard unity types (Vector3, Transform, etc) instead using Unity.Mathematics.math types. I'm sure this is useful with... burst? jobs? ecs? Is there some documentation primer on how to do it?
I used a third party spline package before (which was more "unity-y" in spirit), but would like to stick to the official one, is anyone using it?
Finally got GetBounds to work with trial and error, but ideally I'd want to do something like:
- grab the spline from the splineContainer
- get a new spline that's a copy of the original but with y=0
The Unity.Mathematics types are:
- better honestly
- all have implicit conversations and equivalent memory representations with the Unity engine equivalents
- are of course fully documented in the Mathematics package
I'll have a look at the mathematics package docs, thanks. I know it must be a tradeof of ease of use vs performance, but I was expecting a spline will just be a list of points I would be able to loop through and alter or copy and all of that is probably possible but through some obscure SplineUtility helpers. 🤷
most importantly, they're SIMDd
I wanna make a VR game but I don't really have any coding experience. Should I learn general coding or lean how to code vr games straight off the bat?
What do you guys think is best
You'd get hardstuck without knowing your coding.
Alright so I should learn the basics etc then learn vr
Absolutely, but you can dip your feet into Unity's tools and what templates they provide VR to keep you motivated.
Does anyone have experience using GRFON? Im currently using it to try and handle getting translations for a project but i dont quite understand how to access a key/value pair within a collection.
The documentation has a lot of examples of creating grfon files and their layouts but theres only that one section for reading them in and actually using them so im a little lost.
Ol ok thanks. And do you have any tips or videos to learn coding ??
C# for unity ?
never even heard of GRFON but I guess you are looking for something like
string s = data.GetString("SpellName")
GrfonCollection spells = GrfonCollection.FromString(s);
string fire = spells.GetString("FireBolt")
By the way, should I still use Unity though? I heard is like having a fee of some sort
the chances of that ever affecting you are virtually zero
well first you need to make a financially successful game
Second ?
you would need a really bad accountant once you have achieved first
Oh ok ok and is there a third
Thirdly after earning over a million dollars it would be quite petty to complain about having to pay for the software that made it possible for you to earn over a million dollars
Alr good enough lmao
Thanks guys
Any tips to be good at coding in unity
very long hours over many years will get you so far, sheer talent will get you the rest
Dam. Especially I have a very good vr game idea that I would like to create and buod a team for
Everybody thinks that they have a 'good game idea'. 99.999% of them are wrong
I guess thanks for the motivation 😭
would you prefer I lie and tell you you'll be a multi millionaire by the end of the month? And that game dev is really really easy
I mean nah ofc. Just now I feel like I should not try lmaoo
I mean thanks though
🙌
That is the 'talent' part I mentioned, if you have it you cannot not try
🙏🙏💪
Thanks steve
Hello. Let's say I have a NiceClass niceClass serialized in my script with [ExecuteAlways] attribute. How do I add a listener to it when it was assigned in the Inspector, making sure the listener is added just once and doesn't disappear when the script is reloaded?
I have a clue that the listener is added multiple times in OnEnable
Is there a Path-type class like https://learn.microsoft.com/en-us/dotnet/api/system.drawing.drawing2d.graphicspath?view=dotnet-plat-ext-8.0 that is available in unity? (i'm interested in creating paths and shapes, but not actually drawing them)
I need something that can create closed shapes and test points
Yep
Splines is the package for you
if you mean testing if a point is inside the closed shape, use PolygonCollider2D.
Goal is to create a weird shape with a path, then create a depth map based on that shape to modify my mesh.
not sure what you mean by that, but you've now mentioned three sets of requirements that seem different
They're all the same. I want to generate a random shape that eventually I can use to deform my mesh.
You don't need a library for that
the mesh deformation part will be the much harder piece
you essentially want CSG
There are assets for the CSG piece: https://assetstore.unity.com/packages/tools/modeling/realtime-csg-69542
but the "generate a shape" part - as you mentioned and from the video is just using math to generate a sequence of points.
If you want to be able to sample the shape anywhere along its path - that would be wha the Spline package is for.
This is all runtime generation
Everything done from code.
naturally
I've already written the mesh deformation piece. That CSG tool isn't applicable for me.
thanks. haven't used them before so got a lot of reading to do to add a bunch of curves
Can someone help me with this problem, when i hit the MapBoundary MyRocket is stuck
https://www.youtube.com/watch?v=jLSlGS5kOvM
https://gdl.space/alumasuqot.cs<-- Playerscript infos
https://gdl.space/uvadiromar.cs <--- Map Boundary Script
Your gravity scale is set to 1, you only turn it to 0 if there is no Rigidbody2D on your rocket, and colliding with the boundary is setting isTouchingBoundary to true, which is blocking any movement. Besides that, if you're using a dynamic rigidbody and collider boundaries, then just let the physics handle not going out of bounds instead of doing all that.
Oh, you're setting it to kinematic in your script, but that also happens only if there is no Rigidbody2D present on your rocket. So here it's dynamic and affected by gravity.
How do i manage a componenet on the gameobject i just instantiated from the script
you get back the ref from the component you instantiate
Just store the returned reference and do whatever you want with it
well, assumign you're not instantiating by the GO itself
i can maybe store it in a Variable?
Can anybody point me in the right direction for the following problem. I have a graph of nodes where all such nodes are connected to all other nodes through at least one path. I want to know when removal of one node creates two disconnected sub-graphs.
Choose one node, make a path branching from it to all connected nodes, check if any node doesn't have a previous node
Hello, i need to have the vector that is perpendicular to the ground and was wondering if this is the correct way you would do this?
groundForward = new Vector2(hit.normal.y, -hit.normal.x);
I am mostly wondering if anyone knows the logic of when to use - or not for getting the surface aligned vector?
Do you mean like a modified path finding algorithm that has multiple targets or something? When you find the best route to one you check if the others were also arrived at and continue traversing if not?
I guess you don’t need the best route…
I mean filling up your entire graph with paths
I made something like not long ago, gimme a sec...
I mean if you already know that a node to be removed is part of a connected graph, you only need to know if all its neighbors are still connected after removal right? So you don’t need to traverse all nodes?
I made a procedural ladder. It is composed of two side rails and rungs that get added or deleted depending on the height I specify for the ladder.
When I try to decrease the ladder size, the rungs disappear.
Any idea why this could be happening?
The pieces that make up the ladder were created using ProBuilder.
In a card game if I have different types of cards if I have a common class "cards" but I want some cards to do something and others to perform other functions how should I develope it? I mean, I have a common class to all the creatures but they have subcategories
which perform different functions
In terms of code, any ideas of how should I face it?
Don't cross-post
srry
That video cannot be played on Discord, try a mp4 or online upload - it may also help to post your !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.
Thanks for the head-up! I haven't used Discord for some time and I forgot about this.
Np, it happens
Yeah, that makes sense, if you're checking if others were also arrived after finding a route to one of the nodes then it should be fine (unlesss there are some weird connections I suppose). I prefer to just make the paths once throughout the whole graph and check if any nodes were left out (depends on how many nodes there are tho)
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.
private int[] PathFill(Coords startingCoords)
{
int[] pathMap = new int[NODES_COUNT];
Array.Fill(pathMap, -1);
int startingIndex = startingCoords.ToIndex();
pathMap[startingIndex] = startingIndex;
Queue<Coords> coordsQueue = new Queue<Coords>();
coordsQueue.Enqueue(startingCoords);
do
{
Coords checkedCoords = coordsQueue.Dequeue();
int checkedIndex = checkedCoords.ToIndex();
Coords[] connectedCoords = m_nodes[checkedIndex].GetConnectedCoords();
foreach (Coords coords in connectedCoords)
{
int connectedIndex = coords.ToIndex();
if (pathMap[connectedIndex] != -1) { continue; }
pathMap[connectedIndex] = checkedIndex;
coordsQueue.Enqueue(coords);
}
} while (coordsQueue.Count > 0);
return pathMap;
}
Probably not the best solution in the world, but it works, didn't try it out for larger graphs tho (used it only for a max 21x21 board game). Could be modified to include a counter of checked nodes count, which can be later compared to some all nodes count to see if there were any nodes which were not reached. That, or just as you said, checking connections between neighbours of the node to be removed
🙂
If I set the rigidbody to Kinematic, everything works great. Initially it is set to false, and upon collision with a meteorite it is set to true, resulting in the destruction of the rocket. The problem now is that the limit no longer works because there is no rigid body that behaves as if it were dynamic. However, when I choose a dynamic rigid body, even if the gravity scale is adjusted, all the parts start to fall, or it happens that the parts do not move together. Here are all the scripts and a video.
https://gdl.space/utalucucuy.cs PlayerScript (Rocket)
https://gdl.space/xafuwozure.cs BoundaryScript
https://gdl.space/vojajuvoge.cs Rockpart (Wings,Body,Engine,Arrow have that script)
Hmm that's interesting because kinematic usually makes it not work
Yes, it's the boundary script that actually just makes a Box2D game object invisible and it needs the rigid body features, but the kinematics disables many rigid body properties and that's why the boundary script no longer recognizes my player because my player comes from an empty one Game Object has no real collider, and then when kids see the video history, they all have a rigudbody and a polygon collider, and in the playscript it was written so that the kids are the hitbox of the empty game object, but when I put the kids on in a filmic place then nothing works
but I still can't come up with a solution
Hey all I'm currently attempting to make an x-com like project. I have pathfinding and the like working for multiple floors, however I'm a bit stuck with props. For example, each node in my graph structure can potentially contain a character, which is fine, however what if I have a prop on the node like a box? I want to be able to get a character to jump on the box or be able to move it, destroy it etc. Would anyone have an idea as to how this could be done/what sort of data structure would be best? Right now my box is just sort of sitting in the way haha
I'm currently thinking that I can add a node to the top of the box at runtime and from there the node on the box can work out what neighbours it has
How about just an array of NodeContents objects, where NodeContents defines what is in it and their relationship?
You could probably define the pathfinding distance from one node to another node based on their contents.
As well as whether there is connectivity.
I was considering that too; having an array of items within a cell contents, although I'm not entirely certain how I would establish the relationship in the first place. Maybe I can get the cell to just raycast up until it hits a roof or the sky and say everything that's not those is linked up
Yeah I guess it’s dependent on your level editor or however you generate levels. You could have the relationship be the “ground truth” of your model and place objects based on that relationship rather than placing objects first and detecting relationship based on placement…
So like just start with “box at 63,10” and the engine will generate and place the box that way…
Yeah I could try that out too. Thanks for the information; I'll see what I can sort out
Push
why do i get this error when i drag in a script from my custom package into unity?
It says there's some compile errors but im not sure how to debug this since the script name and class name in script is same so that's not the issue. 
The error doesn't say there ARE compile errors, it says CHECK FOR. However, your console shows there are no compile errors
It should behave as you are expecting it to if you set the parent object "Rocket" to Kinematic and remove the Rigidbody 2D from the child objects.
@charred ruin i try it wait
You might need to do the same for Polygon Collider and I noticed you have a custom script attached. Not sure what's in it but that might have to go at the parent level too.
https://www.youtube.com/watch?v=2utnRlPjpcE
the problem is the rocket is now not exploded in many objects look
new video
When I remove the Ridigbody, the parts no longer fly through the air
Within Unity C#'s framework, is there a property where I can assign a new layer to the gameobject?
when i import my pixel art and make it point no filter it messes up its pixels
oh wrong channel bruh
gameObject.layer is the one
Anyone use DreamTeck Splines? I can't get RebuildImmediate to work without waiting a frame.
For anyone searching this in the future... you need multithreaded=false, autoUpdate=true, updateRate=0f, and then call RebuildImmediate(true, true)
can anyone tell me how to make this coroutine loop properly
its on an enemy that dashes towards the player and then waits a couple of seconds then does it again
What is the point of && true
oh shit i forgot to remove that
i got rid of that I was just spitballing atp
ignore the && true its just time < seconds
it already does basically what I need it to do, but i need it to keep happening. I know how to use waitforseconds but I'm not sure how to in this context
Could just wrap it in another loop that has a wait in it for however long you want between runs
I still would need the time, start, and pos variables updated
float steeringVel = Vector3.Dot(sp.right, worldVel);
//Debug.Log(Mathf.Abs(steeringVel));
if (Mathf.Abs(steeringVel) >= driftSensitivity) steerGripC = steerDriftGrip;
else steerGripC = steerGrip;
float velChange = -steeringVel * steerGripC;
float accel = velChange / Time.fixedDeltaTime;
Rigth here I am working with a custom car controller. I have it pretty much all down besides drifting. My current idea is to check the lateral velocity and if it exceeds a threshold. It works fine but the physics do not. Usually when I lower the tire grip it slides/drifts like normal. But when I do this from high grip to low grip it will end up doing a weak ass turn with what seems like full grip. Any ideas? Thank you
this accel is applied here rb.AddForceAtPosition(sp.right * tireMass * accel + sp.up * force /*+ sp.forward * torque*/, sp.position);
Also note that Unity's Lerp is clamped, you don't need to clamp the t value yourself
hey so
When I add a gameobject to another gameobject
For some reason the first one's position on the editor gets assigned to the child's position
why?
before and after adding the sword to the empty gameobject's
Hello. I want to add a persistent lives and score canvas into my project. The problem I have now is that for some reason, when I die for the first time, the countdown for lives dissappear at 2, but when I die again, the countdown is shown again at 1. What should I do?
Edit: it was the font's problem
Hi. why my EventSystem.current is null when I click with this clickable view?
public class ClickableView : View, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler,
IClickableView
sounds like you do not have an event system gameobject
when i click to default ui button EventSystem.current is not null
are you checking play mode? follow the stack of the original error
Change the transform mode to pivot. You probably have it set to center.
So, my mistake, current is not null, but currentSelectedGameObject is null
ur not working with a gameObject but with UI
I prefer string collection instead of enums for this situation, what do you think?
I want to implement a generic class with different enums. I can use the generic one with T: Enum but if it is string, it would be so easy to handle it, it is more flexible. Another scenario is animation name/type.
What do you think?
Using enums has some limitations while string does not
// enum implementation
_animationController.Play(CharacterAnimations.Shoot)
_animationController.Play(AnimalAnimations.Eat)
public class AnimationController<T> where T:Enum{}
It worked
So, I made the cape cloth, and since i didn't know how to make those dangling thingies, to be dangled and with physics, so i made them cloth too (so you can already see it's not working as intended since it'll deform, and it's meant to be straight)
does anyone know what component do i have to use?
got this piece of code, off chatgpt
it seems to be working fine pointA and pointB share the same y position
how do i make it add a y offset perpendicular to the direction between pointA and pointB?
Posted this in mobile channel but that is very much a non active chat these days. I have a really annoying issue with the simulator resizing itself and scaling itself incorrectly when the window is resized (2022.3.X). Anyone know any fixes and / or work arounds that dont involve just randomly jiggling the window until it fixes itself?
Press Z
messagepack 😎
Depends on the context
custom binary serializer
I see
Question, how can I make the animator to call the OnStateExit methods of its StateMachineBehaviours when the gameobject which contains the animator is disabled?
But I'm using state machine behaviours instead, which support write custom code which is then executed in callbacks.
Also, I'm quite sure that animation events also don't get called if the animator is disabled (they already don't get called if the state is transitioned from before it exits, unlike OnStateExit which does)
ahh I see
How do you guy save non monobehavior classes that are instantiated?
specifically classes that use unity objects such as textures materials etc
you have to call it from somewhere else . . .
Like at runtime?
I have created a main scriptableobject which contains all the textures to be used and creates a unique ID for said textures...
then I simply serialize the ids.
However, said instances are instances of an INTERFACE...so JsonUtility cannot be used
Yes, its runtime
You can override the serialization logic of the JsonUtility for the desired objects.
If you generate new textures and want to save them, you'll need to save them as PNG or something similar probably. As for materials, create a custom class to serialize and recreate a new material from it on loading.
Then just save the IDs
How would I know the type before deserialization/
serialize the type as well
If it's really needed. Because if you override the serialization, you should have control over what and how you serialize/deserialize.
where can i find more info on the override? cant see on internet
The idea is that Unity calls that method automatically...
Anyway, OnDisable seems to work in this behaviours
Yeah, use OnDisable.
OnStateExit is called when you exit the state (and only when you exit the state)
I thought it would work, because when an animator is disabled, its states is reseted, which means that in theory, the current state is exited.
https://docs.unity3d.com/ScriptReference/Animator-keepAnimatorStateOnDisable.html
ah, I forgot that this defualts to false
Does anyone have a good resource for limiting framerate without disabling vsync? I'm handling it like this right now for end users but I really would like to not have to disable vsync if it's possible. Trying to find good info online on this topic is like trying to bleed a stone 😅
I appreciate the time. Yeah this is all I'm able to find on the matter, but this either requires disabling Vsync or using arbitrary values based on screen refresh rates. I'm looking for ways to limit to 30 or 60fps regardless of the screen refresh and without disabling vsync 🤔 Such a pain that this isn't more simple to do
I move my character's arm with the help of a target. this target moves with raycast, but this method does not work when it does not touch a different object. How can I do it with a method?
Ray ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit)) {
aimTarget.position = Vector3.Lerp(aimTarget.position, hit.point, 10f * Time.deltaTime);
}
try this;
float lookX = playerInput.lookX * mouseSensivity * Time.deltaTime;
float lookY = playerInput.lookY * mouseSensivity * Time.deltaTime;
transform.position = cameraRoot.position;
xRotation -= lookY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * lookX);
something like cs else { aimTarget.position = ray.GetPoint(100); }
and replace 100 with whatever distance you want
or you can use the same Lerp thing you have currently just use ray.GetPoint(100) in place of hit.point
I get the occasional stutter. It doesn't seem to give a completely healthy result.
playerBody.Rotate(Vector3.up * lookX); should I replace player body with playerrigidbody?
show code
It would be better to define the variable as Transform, not as Rigidbody.
Ray ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit)) {
aimTarget.position = Vector3.Lerp(aimTarget.position, hit.point, 10f * Time.deltaTime);
}
else {
aimTarget.position = Vector3.Lerp(aimTarget.position, ray.GetPoint(100), 10f * Time.deltaTime);
}
well how far is the thing you're hittin when you switch over to not hitting anything?
It looks like your raycast distance is unlimited right?
try a further distance like 1000 and see if that's any smoother
horizontal rotation doesn't work but it seems stuttering stopped
Okay
Bump
I tried to make 5 with 1000 and 5 was working a little better, but the stuttering was still there.
🥰
well one issue is you're not using Lerp correctly. Try MoveTowards and/or SmoothDamp
Any alternatives to ZipFile.ExtractToDirectory for unity that I can yield from using coroutines? Using webgl and apparently I can't use async operations.
so my options right now looking at, chop the zip into little bits, or let the main thread freeze for 10
I actually think the best path forward is probably to write it in JS and use this https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
oh no js
x__x
I guess that's what it's looking like. Itch.io requires a lot more internal zipping as it'll not accept all of it in your streaming assets.
Anyone has or know where to find a code snippet of a rigidbody following a transform using .AddForce(), seems like there's a few things that would go into doing this and I can't quite wrap my head around it.
It's kind of a second level derivative problem and it kind of depends what your goal is
are you trying to make it intercept the target?
Or keep a specific distance or offset?
or what
It's a second level derivative problem because:
- What you want to change is position
- What addforce directly changes is actually velocity, which later changes position over time
I'm thinking about having multiple entities following each other making a compeling line, so the 'leader' just goes at a set speed and be non physic based, could implement some wait if it's too far away or whatever
each individual has a set max speed, so no offset, it just tries it's best to keep up
i can do that fine using MovePosition but it defeats the purpose
The basic idea though is you figure out the desired velocity you need (based on position and direction to the target), compare that with your current velocity, then apply a force to correct that discrepancy
Like for example, in FixedUpdate
Vector3 targetPos = target.position;
Vector3 currentPos = rb.position;
Vector3 direction = targetPos - currentPos;
Vector3 desiredVelocity = direction.normalized * maxSpeed;
Vector3 currentVelocity = rb.velocity;
Vector3 desiredVelocityChange = desiredVelocity - currentVelocity;
// The most we could change velocity given our max available thrust force.
Vector3 bestVelocityChange = Time.fixedDeltaTime / rb.mass * maxThrustForce * desiredVelocityChange.normalized;
Vector3 actualVelocityChange = Vector3.ClampMagnitude(bestVelocityChange, desiredVelocityChange.magnitude); // don't change more than needed
rb.AddForce(actualVelocityChange, ForceMode.VelocityChange);```
I used ForceMode.VelocityChange here but factored in deltaTime and mass manually so it's effectively a normal AddForce.
I made this very verbose too, to try to make it easier to read/understand
for some reason the videoplayer components just dont stop with this
videos = GameObject.FindGameObjectsWithTag("Video");
foreach (GameObject video in videos)
{video.GetComponent<VideoPlayer>().enabled = false;}```
i also tried Stop() beforehand but that did nothing
Have you done any debugging? Is the code running? Is it finding the objects you expect it to find?
it runs and has no errors popping up
it just doenst stop the videoplayers
By the way, I have another problem. Only the charactercontroller has collision, my weapon etc. there is no collision. But I encounter this problem, do you have any idea about this issue?
That's not what I asked
you need to do some debugging
what do you mean specifically by that? because ive definitely tried to fix the issue and see whats wrong with it myself as much as i can before i came here
that method is a convenient way of doing it all in one go but you don't have to use it, you can always iterate through the entries in the archive and read from the streams bit by bit and spread the work over many frames... that would probably be slower than making the browser do it, but also should be simpler to implement
debugging is just the process of examining the program and trying to figure out what's wrong. You need to, for example, use log statements to print things and see if everything is as you expect. For example print the length of the objects FindWithTag finds and print their names to make sure it's finding all the objects you expect it to find
so your entire advice was "have you tried fixing it yet?"
no
it wasn;'t
it was
take concrete debugging steps like adding log statements
You seemingly have not done so yet.
log statements have one come up for each of the loaded videos
so its definitely finding them
I don't see any logs in your code
just doesnt stop anything
yeah well i didn thave them in there when i did that because i was changing it around a lot
Well boyz, I did it!,
I finally serialized my custom class...only took me 1 week 🙂
Why would you remove them? Share your debugging attempts and what you found will get us to the solution 100x faster.
otherwise we will waste time following down the wrong path
well how about lets get to what im meant to do now
So you have verified that your objects are actually being found?
i already said that doesnt stop them
Then perhaps you're calling it on the wrong objects, or perhaps you have some other code restarting them
or maybe you have some errors happening
When and where is this code running
and when and where do the videos start playing
Share some screenshots of how this scene is set up and where these objects are and which script is doing this and when?
How can i check if a button is selected?
that code i shown is in the gamemanager
the part that plays the video is in here
the videoplayer is displayed on an object called fullscreenvideo
the videoplayer component is inside the button that these events are on
closevideo is just the button that activates the code in gamemanager i shown
Can I ask why you directly reference the object for the play button but the stop button calls this code that finds it by tag?
Just curious
i tried just directly referencing each before but that didnt work and is why im at finding by tag now
i did that bit yesterday so i forgot about it
hey sir !
i just tried having the play vidoe button do its stuff in the gamemanager too even though it shouldnt really do much (?) but its at least a bit neater
didnt change anything
can somone help me?
i think i remember looking into that one it just being impossible for some stupid reason but ill try again
is it even posible?
EventSystem.current.currentSelectedObject```
yes
what does error say
?
yes
Configure your !ide first before receiving help
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
forgot you guys enforce that
i already tried it
it doesnt work
on my computer at least
It's for your own good to have it configured, and very often an issue is resolved this way anyway
what exactly is the benefit
i managed to get it configured at one point but it went away when i restarted my pc
i didnt see what the fuss was about
auto-complete, telling you about frogloads of errors before you even think of doing something... debugger
it makes your IDE actually useful..
other than a TextEditor
it already has auto complete though
Autocompletion, syntax highlighting, quick help, actual compiler errors being shows from the editor rather than having to compile first.
like this ?
Not in that picture
yeah it does that
if it shows Unity components n such then you're good
Wonder how awful the DX would be if the code was fully white
what exactly can you tell from this that its not configured?
if its that easy to spot idk whats going on rn
maybe the color theme threw them off
The different related keywords would be colored correctly
That's enough reason to believe it's not configured, when that does not work
Is it VSCode?
its vscode
VideoPlayer is the same color as video in the signature for one. They should be different. But that is vs code, so I don't know it as well
Depends on the theme
it normally looks like this but thats default theme, maybe you changed it
(using test code line obv)
Yeah, that's what I'm thinking.
I use vs, so I dunno
if you dont have the light bulb though you're def not configured
Also the argument type is the same color as the argument
types default is Green
the thing I dont like about default theme in VSCode is the light blue for member variables..
In Visual Studio they are default white/gray, blueish is color for local variables
I tried checking if this works in my interactor script, i declared testing as public Vector3 testing = new Vector3(40, 0, 0); and hooked it to the click thingy and it worked if (Input.GetKeyDown(KeyCode.Mouse0)) { interactable.onInteract.Invoke(); Debug.Log("Toggled"); // Apply the rotation interactable.transform.Rotate(testing); but now that I know I could put variable thingy inside the transform brackets, I do not know how to link this thing to the transform command earlier ```
public Dictionary<int, Vector3> rotationDictionary = new Dictionary<int, Vector3>();
void Start()
{
rotationDictionary.Add(1, new Vector3(-30, 0, 0));
rotationDictionary.Add(2, new Vector3(20, 0, 0));
rotationDictionary.Add(3, new Vector3(0, -10, 0));
}``` I assigned int in my interactable script so that I could link it to my interactable's itemID, but dont know how it would interact inside the interactor script, or how would he dctionary reference the itemID to the int inside the dictionary
what are you trying to do, I don't get the question sorry
ah wait
I am not good with words, if ok 
its fine, just need to know more or less the game mechanic
or what you want it to do
I want to connect itemIDs int from interactable to interactor's dictionary, but dont know how, and I want to connect dictionary to interactable.transform.Rotate(dictionary maybe);
it is like, there are cars, carpets and brooms in the scene, i want cars to rotate rotationDictionary.Add(1, new Vector3(-30, 0, 0)); and carpets to rotate as rotationDictionary.Add(2, new Vector3(20, 0, 0)); and brooms to rotate as rotationDictionary.Add(3, new Vector3(0, -10, 0));
it happens on click
and I want to assign if they are 1,2, or 3 (itemID inside interactable) to know if they are cars, carpets or brooms
and I used dictionary to store how they would rotate
but dont know how to link them together 
I could assign 2 to a car (using interactable's itemID) and it would rotate like how a carpet would rotate etc (using dictionary)
but i dont know how to make them work together
is ok? or confusing 
are you talking about accessing from another script or ?
hmhm, this is from the interactor script, the only thing in interactable is public int itemType; and something to make raycast work
oh so do you have reference/access to the script ?
hmm, it is like, I dont know how the value of interactable's itemID relate to interactor's dictionary to change the interactable's position
I dont even know what these itemIDs are for , why not use enums
make it more explicit whats wat
I still don't get the
I could assign 2 to a car (using interactable's itemID) and it would rotate like how a carpet would rotate etc (using dictionary)
so you want the rotations to be inside the dictionary and then you pullup the rotation stored?
it is like interactables are the objects, i have itemID inside interactable, i can assign it to 1,2 or 3, but it wont have effect
i plan to match it with interactor's dictionary of 1,2 and 3
but dont know how they can meet or work together
so that interactable can use dictionary's x y and z
inside dictionary, there are 3 things, but it only have numbers
myRotation = Quaternion.Euler(rotationDictionary[id])
ah, is it inside interactor?
wherever you need to accesss/assign the rotation
interactable.transform.Rotate(xyz); this is the code that makes it rotate when clicked
can I use Transform.Rotate(rotationDictionary[itemID])?
yes, lowercase t but yes
but it is in interactable, would it find it?
that is how you access your V3 values
wdym as long as you have the reference it doesn't matter where you access it from
ah, how do we reference other scripts?
is like this? public Interactable interactable;
ah it makes sense noww

I think I know how to get from other scripts now, I will try
sure thing! lmk if you have any issues
okok 
hmm, why wont it find it? interactable.transform.Rotate(rotationDictionary[itemID]); in interactable, I have public int itemID
wouldn't you need interactable.itemID then?
would it be interactable.itemID(rotationDictionary[]);?
but i need transform thingy
itemID is an integer
you can't invoke an integer
this syntax is very wrong
you're trying to use the indexer operator on rotationDictionary with no parameter, which is invalid
sorry, I dont know
I'm trying
don't just randomly mash syntax together
think about each step individually
first, you need to get the item ID
where does the item ID come from?
ah
interactable.transform.Rotate(rotationDictionary[interactable.itemID]);
is ok?
That looks reasonable, yes.
You get itemID from interactable and use that to index rotationDictionary
then you pass the result to Rotate
I thought the way parenthesis work, it would try and get something from it, and put it inside the [], i got confused
i will try
it worked 
thank you navarone, Praetor, Fen
I'm a bit slow, hope it is ok
no worries gotta start at slow pace, eventually it will pick up if you keep at it
Hello, i use a lot of LocalizationSettings.StringDatabase.GetLocalizedString in my scripts for directly get the translation of the string. Is it bad practice?
yes, much better to get them all at game launch and then use a Dictionary to access them
So i made a LocalizedString _constructFee then get the references and changed like this;
It should be this way as i understand right?
does anyone know how to rapair this
how to get end position of raycast which is not hit with anything and it has length
How to repair what?
myRay.GetPoint(length)```
if you don't actually have a Ray then it'd be rayStartPos + direction.normalized * length
the player passes through objects when they move quickly
You are teleporting them in the editor
that's not going to actually move objects with the physics engine
in game it works same
how are you moving the objects?
I would bet you're teleporting them via the Transform
like when the player falls from a great height he flies through colliders
this is tunneling
No, not really. You are going to end up with huge ammounts of garbage collection doing that
What I'm suggesting is that you make your own Dictionary and get ALL of the localized strings you need in one go and store them in that Dictionary
Typical solutions to tunneling are:
- Switch to continuous collision detection
- Reduce physics timestep
- do manual raycasting in FixedUpdate
- Make your colliders thicker
- Make your objects slower
And make sure you move with the rigidbody, not the transform, unless you want to HAVE to do physics queries to prevent clipping
i build a game with 120fps cap and use this code (or any other rotating code)
void Update()
{
transform.Rotate(0f, 10f * Time.deltaTime, 0f);
}```
and it warps sometimes? Im rotating a camera and the scenery is basically a few long pillars and as the camera is moving theyre mostly passing through screen smoothly but sometimes they warp. i for sure have 120fps so im unsure whats wrong
it cant really be seen on video (on video they always warp bcuz recording took some FPS probably)
Note that just because your motion is adjusted for framerate it doesn't mean you will never have framerate spikes
especially if this is in the editor, you will often experience intermittent chugs
Are you sure you're not just seeing a framerate hitch?
its in build
builds can have framerate hitches too
attach a profiler and see what's going on
And note that this exists https://forum.unity.com/threads/what-is-maximum-allowed-timestep.330116/#post-2139556
hyeah that was just VSync capped at 120fps. it works fine at 60fps cap
seems 120fps was too much
TextAsset text = bundleRef.LoadAsset<TextAsset>("assets/bundles/substrings/" + substring + "_.bytes");
So to load from an asset bundle, even though we need to specify the reference to the bundle, we still need the FULL path to the asset and not the path relative to the bundle?
or rather it snapshots the directory it's built in and you have to navigate that
maybe it's just this asset bundle tool
If I have two closed polygons defined by splines, is it possible to generate a new spline that is the union of the two to create a single polygon? (Currently using Dreamteck)
Help, how do i make an object that is rotating flip when turns 180 degrees?
Hey, sorry it's half a month late, I usually don't check Discord, but I'm the lead eng on Muse Behavior, feel free to tag me in questions, or message on the Unity Discussion pages for Muse which I'm quite active in 🙂
ok, wait, do i have to cast a raycast to know if there is a wall, then make it so the player jumps to the opposite side with 1.5x the jump power to make a wall jump?
This is just for an easy demonstration and not serious development, but yes, find at runtime is no good 🙂
For the original question: Did you assign a blackboard variable to the node and did you assign a value to your variable in the inspector for the gameobject?
Hey, I got quite far and I am actually stuck on much more complicated issues then initially .
The main issue I am facing is switching to the right state at the right time and ensuring the npc does what it needs to. I have been really active is the unity Discussion . You can find the full thread here - https://discussions.unity.com/t/muse-behaviour-getting-started-issues/338435/35
I looked into it, and yes, the Succeeder has a bug in its OnStart() logic. I’ll put the fix in an upcoming release. For now, here’s a working version you can use: [NodeDescription( name: "SucceederFixed", description: "Forces success for the child node.", icon: "Icons/success", id: "2a2fadb041974c9a9bc85921a31f8763")] public ...
I see , well makes sense then 🙂
Oh, Reaper210! Hello 🙂
We've got a fix for the succeeder coming up. I hoped it'll be live today but we're having an issue with the release tool and need help from release management. I was away on vacation for 2 weeks and couldn't chase them and unfortunately I'm not sure why it wasn't followed up. Sorry about that!
I hope the information from Trevor helps otherwise. Did you try with his fix?
Not to worry, I have bit of way more than I can chew with the AI and kinda swept it under the rug for a while .
Completely lost to be very honest
Well, if you want to have a chat sometime let me know and I'll see if I can help 🙂
I would love that. Mind if I DM you when ready ? SHould be in next week some time
Yeah, feel free to, or continue the discussion on the discussions pages so Trevor can also join in, whichever you feel like.
Happy to jump on a zoom call if needed to look into what's going on
Just a note I'm based in the UK so will need to figure out the timezones (don't ask me why I'm responding at 23:42! I care about the project quite a bit 😅 )
Physics queries are required to know if there are physics objects in an area, yes
is there any other way of "raycasting" more effective than casting for every direction? i wanna do an "omni-directional" wall jump
You can use the overlap methods, different shapes of casts, or the check methods
Perhaps OverlapSphere is more what you're looking for?
Or simply attach a sphere collider and add OnTriggerEnter to your code?
I have an enum in a base class of a SO, EffectType is the enum
public abstract class EffectSO : ScriptableObject
{
public EffectType EffectType => effectType;
[SerializeField] protected EffectType effectType;
}
In a specific child class I want to enforce effectType to only be a specific value but I am having problems. I tried setting the value in OnEnable and OnValidate but it seems to go back to the default value after I rename the SO (see video). OnValidate does set it to the correct value properly after i change something but its awkward to do. Id like it to be set right away. I am probably missing something stupid.
What can i do to fix this?
that would be on the code for the collider or the player code?
i presume, when collider enter return something so it can wall jump
this on the collider
Either works. But if you think about it, the player makes a bit more sense, right?
oooohohhhhhhhhhh, thx
need to probably add flags though so it sets once
also could be related:
https://forum.unity.com/threads/trying-to-set-scriptableobject-as-dirty.812616/
I'm having some weird issues with the android resolver while trying to .. resolve. I've just downloaded and installed the ironsource levelplay package and ... the android resolver seems to be having issues with it:
Win32Exception: ApplicationName='D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle\gradlew.bat', CommandLine='--no-daemon -b "D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=D:/Program Files/Unity/2022.3.17f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=D:\projects\unity\2048CE\Assets\Plugins\Android" "-PMAVEN_REPOS=https://android-sdk.is.com/;https://maven.google.com/" "-PPACKAGES_TO_COPY=com.ironsource.sdk:mediationsdk:7.8.1;com.google.android.gms:play-services-ads-identifier:18.0.1;com.google.android.gms:play-services-basement:18.1.0" "-PUSE_JETIFIER=1" "-PDATA_BINDING_VERSION=7.1.2"', CurrentDirectory='D:\projects\unity\2048CE\Temp\PlayServicesResolverGradle', Native error= The system cannot find the file specified.
I can't tell what file isn't found - the SDK appears to be there, although the / is backward on the last part of the dir.. Not really sure what else to look for. Since I've installed the LevelPlay plugin - any android build just hangs, and tailing the editor.log shows it farts on that stack trace then just hangs (45 minutes before I killed the process entirely)
if (joinButton.onClick.GetPersistentEventCount() == 0)
{
Debug.Log("we can add click, this is first time!");
joinButton.onClick.AddListener(() =>
{
MainMenu.instance.Join();
});
}```
why does the debug statement keep printing even after ive added the listener?
this function gets called multiple times btw
add listener doesn't add a persistent listener, but GetPersistentEventCount() gets the persistent listener count
what's the difference between persistent and regular listener?
I don't know exactly but I imagine it's a listener that's serialized in the inspector
Ah
In any case, you can give your listener an actual method, then just add/remove it normally (which you probably should do) in onenable and ondisable
private void OnEnable()
{
joinButton.onClick.AddListener(ClickHandler);
}
private void OnDisable()
{
joinButton.onClick.RemoveListener(ClickHandler);
}
private void ClickHandler() { ... }
thanks, ISerializationCallbackReceiver ended up working. I also tried that setting dirty thing, maybe i misunderstood but it didnt work for keeping the value set during that part i showed in the video
You ever zone out so unbelievably hard that you start doing "is not less than" operators.
Hit em with the
!<
{
rotationDictionary.Add(1, (new Vector3(-60, 0, 0), new Vector3(60, 0, 0))); // Example values for item type 1
rotationDictionary.Add(2, (new Vector3(20, 0, 0), new Vector3(0, 0, 0))); // Example values for item type 2
rotationDictionary.Add(3, (new Vector3(0, -10, 0), new Vector3(0, 0, 0))); // Example values for item type 3
}``` how do I set this up to make it not add or subtract it everytime it happens (to prevent bugs of it overflipping), instead, set it to that vector? like if I click it when on, it will be on that position no matter how many times i click it
is it because it is .add which is why it adds the vector?
can it be .set? i am not sure what to put
man that's not a very useful tutorial
Hi, I have game events that get activated when the player goes through a collider trigger, and the game events follow a path by the waypoint system. But my problem is that they all activate at the start of the game prematurely. How do I fix this? I don't know what's causing this. The code is below: ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IncomingCar : MonoBehaviour
{
[SerializeField] private GameObject pedestrian = null;
// Start is called before the first frame update
void Start()
{
pedestrian.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider Other)
{
if (Other.CompareTag("Player"))
{
pedestrian.SetActive(true);
}
}
}```
here this seems more useful https://www.tutorialsteacher.com/csharp/csharp-dictionary
You mentioned events.
Did you mean those setactive calls?
no, just a simple collider trigger setup with waypoints for an object that follows it when activated
oh wait
sorry misunderstood ur question
thank you prakkus 
yeah pedestrian is the event thing that follows the waypoint
Ok, then the issue is probably that pedestrian starts awake. You can set it to disabled in the inspector before runtime so it STARTS disabled.
Start runs after Awake and OnEnable.
Not sure how pedestrian is supposed to work, but if stuff happens in OnEnable, then disabling it in start is too late
Okay, so I should move the setActive(false) to the inspector before runtime?
Not sure what you mean.
I mean just click the little square to the left of the gameobjects name in the inspector
SetActive can't be moved to the inspector
Or just use ACTUAL events, which are called in OnTriggerEnter
Okay i will try this lmao thought i had to do some fancy code thing
what do you mean?
Well events mean a specific thing in c#, what you are doing isn't actually an event
One sec
oh okay yeah the place i work at calls it "events" cause my boss ain't a unity person
i'll look at that too
the fix seems to work
thanks
Well, Events aren't unique to unity btw. It is a base c# thing
And they exist in many programming languages too
my boss isn't a coder person either
I have a question about coroutines: between these two yield statements, would this segment of code be executed every frame or would it just be executed once?
unless you have a loop or start multiple instances of the coroutine then that code executes only once
ok thank you
any suggestions on how I would make that segment of code loop over a certain time period?
genuine question, do i have to unsubscribe my event when using UnityEvent?
Same as with normal events
what if i assign it through only inspector, not script?
do i still need to unsubscribe?
Use a loop. Make the while condition the time it has taken.
Be sure to have a yield INSIDE the loop (just yield return null for one frame), otherwise it will freeze the game
ah, I still cant figure this out 
I want to make something like rotationDictionary.setexactposition(1, (new Vector3(-60, 0, 0), new Vector3(60, 0, 0)));
Probably not. I don't think you can unsubscribe them, so unity should be doing the required checks itself.
This code doesn't really rotate anything, so it's probably irrelevant to the issue.
ah, so the problem is the toggle thingy?
Why would you want to mess with the values in the dictionary?
What is a toggle thingy?
I assume. I don't know what other code you have.
{
interactable.onInteract.Invoke();
Debug.Log("Toggled");
///interactable.isOn = !interactable.isOn;
// Get the rotation settings based on item type
(Vector3 onRotation, Vector3 offRotation) rotationSettings = rotationDictionary[interactable.itemType];
// Select the appropriate rotation based on the isOn state
Vector3 rotationValue = interactable.isOn ? rotationSettings.onRotation : rotationSettings.offRotation;
// Apply the rotation
interactable.transform.Rotate(rotationValue);```
I thought the dictionary was the problem because it has .add
Add just means put the thing in the dictionary
Yes, this would keep on rotating the object with the provided value.
ah xD i thought add like as in add the xyz also
got confused
Add it to what though? Keep in mind you are adding it TO the dictionary
A dictionary doesn't have a rotation or vector of any kind
It's just essentially a list (not quite) of key value pairs
a bit confused with terms, but i think I get it now
like .add is to put things inside dictionaries but doesnt really do math commands
like add to bookmarks
Correct
also, when i do this interactable.isOn = !interactable.isOn; here on
{
interactable.onInteract.Invoke();
Debug.Log("Toggled");
///interactable.isOn = !interactable.isOn;
// Get the rotation settings based on item type
(Vector3 onRotation, Vector3 offRotation) rotationSettings = rotationDictionary[interactable.itemType];
// Select the appropriate rotation based on the isOn state
Vector3 rotationValue = interactable.isOn ? rotationSettings.onRotation : rotationSettings.offRotation;
// Apply the rotation
interactable.transform.Rotate(rotationValue);
}
}```
it is ok and works fine, but i need to make it so it doesnt flip first without the toggle commands if it is always on so there wont be bugs, like set the xyz to the assigned dictionary and not flip it over and over, but not sure what is causing the adding or flipping over and over, but i have a feeling it is ``interactable.transform.Rotate(rotationValue);`` since it is ".Rotate" and not something like setxyz, i do not know what the function is
Do RigidBodies have a calculatable velocity when the object is being animated?
Or would I have to manually calculate per frame if I wanted a velocity to persist when object's being animated too e.e
does someone know why my gameobject doesnt move?
this is the code
i tried to also move it with the input system and actions but i cant manage to make it work
You are updating the value of movement only once, in Start
You are also trying to catch a single frame input in fixedupdate
just changed it and it doesnt work still
code beginner problem
also dont use getXXdown and up in fixed update
Changed it how?
Floats and Vector2s are value types so you need to keep updating them, since you are working with copies. The line in Start will not magically make movement always use those valus
or any function that not running at the rate as update()
could you explain what does it mean to catch a single frame?
GetKeyDown is true for a single frame
true
FixedUpdate runs at the physics cadence
It may happen less than the frame rate
Meaning it misses the input entirely
so i should change it to Update?
alright
You can get away with it for multiframe input, but not single
Like this? When I run this it actually works, but is this a good way of doing it?
I would not do the waitforseconds in the loop
Like I said, just yield return null
oh ok
You are allocating a new WaitForSecons each loop otherwise
But other than that, yeah that's what I meant
Better update velocity after updating input, not before
Otherwise you are working with last frame's input basically
but even if i getkeydown it still doesnt do it
Hmm also dont think you should use deltatime here
in the last frame i mean
lemme try
a frame delay between each input
btw velocity is m/s if you multiply it with s then it becomes m which is displacement
it works now
i just need to mess a bit with how it works because it glides
since i havent made up a good way to make horizontal and vertical = 0 (i think)
Read (and research) the rest of the errors
idk what i did but i wrote an else afterwards and it just freezes and doesnt move wether i press ASWD or i dont
GetKeyDown is true for 1 frame only. So that else is true for all other frames
GetAxis/GetAxis exists too btw
Using Vertical and Horizontal axis is pretty common
yeah my friend is using those but i want to start as basic as possible
ohhhh
so how should i fix it?
im thinking of making another variant that is getKeyUp ?
(GetAxisRaw if you dont want input smoothing)