#archived-code-general
1 messages · Page 43 of 1
It doesnt help
I may have follow it wrong
I copied that custom script i could return vector3 without issue but still the moment it became a list it explode
hi there, i got quite a problem on my hand. I am trying to make an enemy in a 2d game that would attack with a laser and that laser would follow the player for 5 sec and then stop :
but when the player move
the laser follow him perfectly and i want the laser to take a bit of time to change the direction
Theres no other instances of the script calling it, ive tried assigning it with gameobject.find on awake and start, manually assigning it in the inspector
playerOne.transform.localPosition = new Vector2(1,1);
player one is a public gameobject, tried using transform too
Has anyone had the issue where if you click an error log, it doesn't show you any any actual log and instead rapidly selects a class and spams the console with more of the same exception?
I'm guessing that means the error is inside an update loop?
i didnt understood that
Probably? 🤷
how i have to do it?
you have a reference to the parent gameobject?
you need that in order to set the parent of the newly spawned gameobject
like a [SerializeField]?
ok
[SerializeField] GameObject Generations;
then just do cs Instantiate(building1, new Vector2(buildingPos, hBuilding1), Quaternion.identity, Generations.transform);
worked
thanks
guys in a 2d rotaion space how to make an object slow down when it turns on way and tries to turn the other way?
[SerializeField] float TimeBtwnSpawn = 1f;
float NextTimeSpawn;
[SerializeField] bool _usePool;
[SerializeField] Enemy01 _enemy01;
public ObjectPool<Enemy01> _pool;
private void Start()
{
_pool = new ObjectPool<Enemy01>(() =>
{
return Instantiate(_enemy01);
}, enemy01 =>
{
enemy01.gameObject.SetActive(true);
}, enemy01 =>
{
enemy01.gameObject.SetActive(false);
}, enemy01 =>
{
Destroy(enemy01.gameObject);
}, false, 10, 20);
}
private void Update()
{
SpawnEnemyOne();
}
void SpawnEnemyOne()
{
if (Time.time > NextTimeSpawn)
{
NextTimeSpawn = TimeBtwnSpawn + Time.time;
var enemy01 = _pool.Get();
enemy01.transform.position = new Vector2(Random.Range(-4.3f, 4.3f), 2.73f);
}
}```
hi guys sorry, but how do i so called "remove the game object"? in the old object pooling system, i can just setActive(false) on the script that attached to that object. But this is the new one, it said "_pool.Release();" on that script, but it has a null error
Show the console error.
it said there's a null reference exception error on this line cs private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Ground")) { _pool.Release(this); <---- this line } }
_pool is null
NREs occur because a variable has attempted to access it's member but has not yet been properly assigned a reference or is currently assigned a null reference.
oh ok. now i put ? after _pool, it works ty but now it didnt disappeared.
erm.... i think i wanna give up on this new input object pooling system. It's so complicated. Sorry but is the old object pool system is as good as the new one? in terms of garbage collecting or FPS dropping etc? because if its as good as new one, i will jsut use the old one haha
I'd use whatever works.
oh ok. so the object pooling is still as capable regardless of old ones as to new ones. okok thanks
But to solve your issue above, it's likely that the callback method (physics collision method) isn't on the same object as the one with the object pool.
Where you'd simply need to reference the object above with said script component and then you'd be able to access the public _pool member.
ohhh okok. i think i get it! thank you!
How did you do that with uh below with big black background?
on discord, I mean*
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Read the "Inline Code" section of the bot's message above^
Ohhh, I get it now!
So I tried to make a coding on the character to walk properly (Down, Left, Right, Up) with an animation so I made a script for it, it has no issues but seems like it won't work on it since the character just walk with straight line
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private bool isMoving;
private Vector2 input;
private Animator animator;
private void Awake()
{
animator = GetComponent<Animator>();
}
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
Debug.Log("This is input.x" + input.x);
Debug.Log("This is input.y" + input.y);
if (input.x != 0) input.y = 0;
if (input != Vector2.zero)
{
animator.SetFloat("moveX", input.x);
animator.SetFloat("moveY", input.y);
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
} ```
Ok, so, I am currently making a grand strategy game, and I've made a system which can load provinces from an image file, similar to what you'd see in a paradox grand strategy game, it all works, there's no problem with that. I can get all the information of a province by simply clicking on it, and it's relatively performant, great stuff.
Now, my issue is, that I need to, like, overlay these provinces with the color of the country they are apart of. And I am not asking how to do that, it's probably very complicated. I just have no idea what to search for, so I am looking if someone more experienced than me could lead me into the general direction, since I believe that just storing the pixels of the province and then having a second texture on which I paint those pixels everytime I need to change the color, doesn't sound that performant, and I am sure there is a better way to do it with like some kind of shader which associates 2 colors or something.
Hey Guys I am having weird issue with Unity, So I am making a runner game, and I have a layer for objects I want to kill the player, Problem is part of the colliders is a vehicle, I want players to only be killed by front part and be able to climb the roof, so I created an empty game Object in the vehicle prefab, set the collider the position of the roof, then set the layer to be default so it doesnt kill the player, problem is that it makes the rest of the vehicle not kill the player whereas other parts are set to the layer thats supposed to kill the player what could be the problem
if i run code OnEnable, shuld i also run it on Start? i know start runs once and never again but does OnEnable run when Start runs?
OnEnable will run before start
but also every time the gameobject becomes active again (unlike Start that only ever runs once)
What is the best way to check if the player is moving to change the animation to a walking animation? I tried checking the distance between the current position and the last position but its saying the player is moving when its idle. Any ideas?
You could do it directly where you read the input
Or do movement forces
And change the Animator's parameter there
Yeah I thought of that, but I'm not sure if that would as performant as other methods
What do you mean by this?
Probably more performant than a distance check 🤔
Like where you move the character. Feed those numbers directly to the animator
But if you need to check distance (to avoid walking while not moving, feet sliding etc), you can do it
Hmm..
Unity doesn't have a function to check if a key is held down so I would need to keep variables for W A S D when they are pressed and released and then compare those values to see if any of them are not pressed down so I can change from Walk to Idle animation
Unity doesn't have a function to check if a key is pressed down
Wat
I'm using Unity's new input system
You can only check if keys were pressed the frame
Unless if it checks if its held down
I'm pretty sure you can poll input with the new system too
Is wasPressedThisFrame true if the key was pressed in a previous frame and is still held down?
Looks like you can use context.ReadValueAsButton
Even if not, you could store it in a bool
Yes I know
Oh yeah you mentioned keeping it in a variable
But then like I said, each frame that would be checking 4 variable if they are pressed down and if they have been released, and then checking if any are still being held. I am explaining this horribly but it doesn't sound very efficient ._.
No I hear what youre saying. But hmm you could just update the animator parameters right as you receive the input?
No need to store it anywhere
Im curious though how your character is moving then? Don't you already have variables for its movement direction?
Uhh
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
move = transform.right * x + transform.forward * z;
controller.Move(move * newSpeed * Time.deltaTime);```
That is what I have
Also this is what I meant before by using variables...
if (Keyboard.current.wKey.wasPressedThisFrame) wPressed = true;
if (Keyboard.current.aKey.wasPressedThisFrame) aPressed = true;
if (Keyboard.current.sKey.wasPressedThisFrame) sPressed = true;
if (Keyboard.current.dKey.wasPressedThisFrame) dPressed = true;
if (Keyboard.current.wKey.wasReleasedThisFrame) wPressed = false;
if (Keyboard.current.aKey.wasReleasedThisFrame) aPressed = false;
if (Keyboard.current.sKey.wasReleasedThisFrame) sPressed = false;
if (Keyboard.current.dKey.wasReleasedThisFrame) dPressed = false;
if (wPressed || aPressed || sPressed || dPressed)
{
animator.SetBool(idleAnimID, false);
animator.SetBool(runAnimID, true);
}
else
{
animator.SetBool(idleAnimID, true);
animator.SetBool(runAnimID, false);
}```
Actually I could use else if's which would make it a bit better but still lol
Oh I assumed you were using Input actions
Which are event based
You wouldn't have to poll it
I don't know how to use those 😂
You are massively overcomplicating this.
How should I do it then?
Use an input action
Idk how ._.
Bind it to the up/left/right/down composite of those buttons
Follow the pinned tutorials in the input system channel #🖱️┃input-system
Recently stumbled upon this video (https://www.youtube.com/watch?v=Jufdyjl6poo&t=219s) and was quite intrigued by the section on a multi scene workflow. I cant seem to find many resources on setting up such a thing, so wondering if anyone on here knows of any more comprehensive resources or reading on this topic. Thanks
Sign up to Milanote for free with no time limit: https://milanote.com/gamedevguide - Let's explore 5 things you can do to improve how you're working in Unity. Got any tips of your own? Let me know below 👇🏻
Better Version Controls:
Plastic - https://www.plasticscm.com/
SVN (Subversion) - https://subversion.apache.org/
Perforce (Industry Standar...
I still haven't found anything, if somebody knows anything, any help is appreciated.
Just drag a scene into the hierarchy
Whenever I make a build for a game and I have unused assets in my project, does my build include those unused assets? If so how do I make it to where those unused assets don't get included?
Generally unused assets are not included
https://docs.unity3d.com/Manual/ReducingFilesize.html
So I shouldn't have to worry about migrating unused assets anywhere or anything like that when I make my builds?
so i am trying to generate objects in a grid position between the origin point of the transform,but it doesn't instantiate completely,but stops at like a distance of 1-2 units from the mouse,for context the grey knob is the mouse position when clicked
var size = Input.GetKeyDown(KeyCode.LeftShift) ? (mousePos - transform.position).normalized : (mousePos - transform.position);
Vector2Int completeSize = Vector2Int.RoundToInt(size);
for (int x = 0; x < size.x - 1; x++)
{
for (int y = 0; y < size.y - 1; y++)
{
testObjects[x,y] = Instantiate(testObject, new Vector2(x, y), Quaternion.identity);
}
}
also i am using ScreenToWorldPoint
why are you doing size.x - 1 and size.y - 1?
as the 2d array is instantiated at the size variable,but now that i think about it,i should try adding one to the variable
you should be doing CeilToInt and omit the -1 or FloorToInt and include the -1 (not RoundToInt)
var size = Input.GetKeyDown(KeyCode.LeftShift) ? (mousePos - seekerRigidBody.position).normalized : (mousePos - seekerRigidBody.position);
Vector2Int completeSize = Vector2Int.CeilToInt(size);
testObjects = new GameObject[completeSize.x + 1, completeSize.y + 1];
for (int x = 0; x < size.x; x++)
{
for (int y = 0; y < size.y; y++)
{
testObjects[x,y] = Instantiate(testObject, new Vector2(x, y), Quaternion.identity);
}
}
so something like this?
testObjects = new GameObject[completeSize.x, completeSize.y];
for (int x = 0; x < completeSize.x; x++)
{
for (int y = 0; y < completeSize.y; y++)```
yeah that's better,but is there a way to make it so that numbers like 1.1 turn into 2 instead of 1?
i want to make sure that a cube is always instantiated regradless of grid size
that's exactly what CeilToInt does
Hey Guys.
I'm working with UI right now and i have a scroll list in which i instantiate some prefabs on start.
Thing is. Those prefabs have buttons that i need to change/register the callBack function from.
Thing is. im adding a function as a listener and its going in the function
here is the code ```c
public void ShowFreeSurvivors(Transform activityTransformIcon)
{
survivorScrollView.parent.gameObject.SetActive(true);
foreach (Survivor survivor in survivors)
{
Transform child = survivorScrollView.GetChild(0).GetChild(0).Find(survivor.name);
if (child == null)
{
Debug.Log(survivor.name + " returned null, something is wrong with survivorManager");
continue;
}
if (survivor.isBusy) child.gameObject.SetActive(false);
child.GetComponent<Button>().onClick.AddListener(() => OnSurvivorSelected(activityTransformIcon, survivor));
}
}
private void OnSurvivorSelected(Transform activityTransformIcon, Survivor survivor)
{
Debug.Log("Got in here");
activityTransformIcon.GetComponent<Image>().sprite = survivor.icon;
survivorScrollView.parent.gameObject.SetActive(false);
//next we are going to have to pass the survivor to the activity so he can run it whenever player clicks on run button
}
What's the issue?
Debug never prints, buttons dont do anything. no callback function is register on the inspector
- no callback function is register on the inspector
This part is expected
the scroll list goes up and down tho
adding listeners with AddListener won't add one to the inspector
that's only for persistent listeners
uhm ok. good to know!
Use Debug.Log to make sure you're getting to the code that calls AddListener
im getting there already done that
button is there as well
doesnt return null i mean
maybe The foreach loop is never running (ShowFreeSurvivors never called)
or survivors has no children
see if you can get a positive Debug.Log after that null check
nah, they have.
ok - does your button react at all to the mouse?
Does it animate/fade/change color/etc?
no, not at all
sounds like you're missing Event System in your scene
it is interactable
nah that's fine cause other buttons work
only these ones doesn't
then something is blocking this one
another UI element
or the canvas it is on is missing a Graphic Raycaster
keep your EventSystem selected and look at the preview window at the bottom of the inspector while the game is running. Observe what the preview window says about which object(s) the mouse is hovering over
Bingo my friend
Another part that is work in progress was blocking it. another panel that i still have to populate and add into the navigation logic.
Thanks! Owe you one!
you are right,but as you can see,there still an area where the squares don't occupy the mouse position
How do I convert quaternions to euler in JavaScript ?
I'm receiving the quaternions x, y, z and w values on a website, I want to convert that into euler angles. How do I do that ?
Good afternoon
I try make a game of sumô
And my codings not working
Movimentation:
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Collider))]
public class Movimentation : NetworkBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
private bool isGrounded = true;
private Rigidbody rb;
public GameObject player;
void Start()
{
rb = GetComponent<Rigidbody>();
if(isLocalPlayer){
rb = GetComponent<Rigidbody>();
rb.centerOfMass = new Vector3(0, -0.5f, 0);
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
void Update(){
if(isLocalPlayer){
Stabilization();
}
}
void Stabilization(){
if(Input.GetKeyDown(KeyCode.M)){
Vector3 newRotation = new Vector3(0f, 0f, 0f);
player.transform.rotation = Quaternion.Euler(newRotation);
rb.Sleep();
}
}
void FixedUpdate()
{
if(isLocalPlayer){
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput) * moveSpeed * Time.deltaTime;
rb.MovePosition(transform.position + movement);
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ground") && isLocalPlayer)
{
isGrounded = true;
}
else if (other.gameObject.CompareTag("Player"))
{
Vector3 repulsionDirection = transform.position - other.transform.position;
rb.AddForce(repulsionDirection.normalized * 10f, ForceMode.Impulse);
}
}
}
Câmera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class FirstPersonCamera : NetworkBehaviour
{
public Transform characterBody;
public Transform characterHead;
float sensitivityX = 70.0f;
float sensitivityY = 70.0f;
float rotationX = 0;
float rotationY = 0;
float angleYmin = -80;
float angleYmax = 80;
float smoothRotx = 0;
float smoothRoty = 0;
float smoothCoefx = 0.85f;
float smoothCoefy = 0.85f;
public Camera playerCamera;
void Start()
{
if(isLocalPlayer){
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
if(!isLocalPlayer){
playerCamera.enabled = false;
}else{
playerCamera.enabled = true;
}
}
private void LateUpdate()
{
if(isLocalPlayer){
transform.position = characterHead.position;
}
}
void Update()
{
if(isLocalPlayer){
float verticalDelta = Input.GetAxisRaw("Mouse Y") * sensitivityY;
float horizontalDelta = Input.GetAxisRaw("Mouse X") * sensitivityX;
smoothRotx = Mathf.Lerp(smoothRotx, horizontalDelta, smoothCoefx);
smoothRoty = Mathf.Lerp(smoothRoty, verticalDelta, smoothCoefy);
rotationX += smoothRotx * Time.deltaTime;
rotationY += smoothRoty * Time.deltaTime;
rotationY = Mathf.Clamp(rotationY, angleYmin, angleYmax);
characterBody.localEulerAngles = new Vector3(0, rotationX, 0);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
}
}
What? You're not using unity?
And my players are flyng in arena
Somebody help?
I am, I'm sending object in JSON form to a website.
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
When we convert the transform component to JSON, it is in this form:
Googling "quaternion to euler angles" yields a Wikipedia page first result, in which if you scroll down, shows a C++ example converter method
in m_LocalRotation the object's rotation is in quaternions.
I'm using a quaternion-to-euler package, but it's giving some wrong results. Maybe the coordinates order is different in unity
?
That's some info that should have been included in your original post
The 4 values on top are x, y, z, w respectively
the array is the generated angles
it should be [45, 0, 0]
Use a bin or paste site to put your code then send us the links. The code you put takes up too much space in chat . . .
Unity's axis setup is not standard, the vector should be rotated so Z faces up, and Y forwards
console.log(x, y, z, w, qte([z, y, x, w]).map((a) => a * (180/3.1415926)));
i need to make an item representation of a weapon, but i also need to store levels. should i use scriptable objects for this? in the past i had to do weird workarounds because scriptableobjects aren't modifiable
should i use scriptable objects for this?
no, use prefabs
thanks
there are a few approaches to this
take a look at prefab variants
you can variant out the UGUI and in-game representations of your weapon
e.g.
Well I'm not really sure I've tried every xyz combination in qte([x,y,z,w]) function:
Expected: [45, 0, 0]
x,y,z,w [0, 0, 135.00000648410892]
x,z,y,w [0, 0, 135.00000648410892]
y,x,z,w [0, -45.00000177679052, 180.000003070469]
y,z,x,w [45.00000088625341, 0, 180.000003070469]
z,x,y,w [0, -45.00000177679052, 180.000003070469]
z,y,x,w [45.00000088625341, 0, 180.000003070469]
your project folder:
Role Name of Asset
[1: Prefab] Base Weapon
[2: Prefab variant of 1] AK47
[3: Prefab variant of 2] AK47 (UGUI)
[4: Prefab variant of 2] AK47 (Playermodel)
[5: Prefab variant of 2] AK47 (Dropped)
for example, here is the hierarchy of AK47 UGUI
AK47 (UGUI)
Inspector: Weapon Component
AK47 Component
[+] RectTransform
-> Image
-> Text Label
...
ultimately scriptable objects will be low value. the 3 fields of the weapon name, its cost or whatever - that stuff is not saving you any time to build this whole thing around. you'll still eventually need to make a bunch of prefabs representing the weapon in different contexts.
thx!!!
@vale wren so when you save levels, you meant upgrades for the weapon right? I suppose those could be components on the AK47 prefab. those will automatically propagate down to the prefab variants. that way, when you want to visualize the current level, you can add an object to AK47 (UGUI) like a label that references those
yeah exactly
to "turn" a UGUI into a Dropped weapon is trickier - you might want a different hierarchy, one where you separate the logical part from the graphics part. so something like
AK47
Logical
Graphics
UGUI
AK47
Logical
Graphics
Dropped
AK47
Logical
Graphics
Playermodel
for the sake of designing easily, you can keep these as prefab variants. then, in game, when you want to "drop" an item, Instantiate the Logical game object (which copies it), then instantiate a fresh dropped graphics and destroy the ugui graphics
this is fine if you really want to commit to the Unity way of organizing your game, it will work and it will take advantage of editor features
and not be painful
but it will make it a little harder to know what's going on, because it's hard to enforce a hierarchy in the editor as opposed to code*
if all of this stuff is pretty lightweight, you can have one prefab of this form: all three graphics are present. then toggle between them and don't Instantiate.
AK47
Logical
Graphics
UGUI (active)
Dropped (inactive)
Playermodel (inactive)
this is what i usually do
it's tricky because AK47 expects to be recttransform2d to be on a UI - so in reality, UGUI is always separate
and has a reference to an AK47 game object that lives in 3D space but has no graphics
this is a very ECS approach. indeed, ECS is really good for making something like an FPS
@vale wren hope this helps
thank you!!!! this is a much cleaner system than whatever the hell i was doing before
lol
okay cool
this recttransform thing is going to be a pain point
just a heads up
remember at runtime there are no prefab variants, and you can also move things around. i suggest designing with the UGUI object, then moving it at runtime into your UGUI hierarchy. it will still reference the correct weapon.
so something of the form
AK47
Logical
Graphics
AK47 UGUI
when you hit play, move the UGUI object where it needs to be. then this becomes
AK47 (Clone)
Logical
Graphics
Camera
Canvas
Panels
AK47 UGUI
this way you can set the sprite of the icon right on prefab. you don't need to create a scriptable object with a reference to a sprite
AK47 UGUI itself can be a prefab variant of an Item so all you're doing is overriding the sprites
this code not work WHYYYYYYYYYYYYYYY
that way if you want to change the look of the icons in your inventory gradually, you can
you should learn how to write a for loop
you can replace hundreds of lines of code with 3
@vale wren prefab variants, used wisely, are like a superpower and obsolete a lot of scriptable object workflows for your early game development
prefabs are nice when most of the work is defining a weapon's behavior as a composition of other smaller pieces.
ok
lots of advantages.
almost turned into stone looking at this
but it doesn't work because what, the number of lines doesn't matter my code is super
huh
your code is insanity
it was written by a raving mad lunatic
😭
oh god I made the mistake expanding it
no I am just new
you also never explained what you mean by "it doesn't work"
what are you expecting it to do
what does it do instead
i have a collision-based flag in LateUpdate that should get initialized by code executed in OnTriggerStay, and according to the unity docs on the order of execution, OnTriggerXXX gets called first beforeLateUpdate. however, during playmode, the the script is behaving as if LateUpdate gets called first before OnTriggerStay, resulting in the flag not getting initialized before LateUpdate code executed. this behavior occurs inconsistently between entering playmode, where the flag sometimes gets initialized by OnTriggerStay before its used by LateUpdate, and sometimes it doesn't. any ideas as to how to resolve this issue??
the size of the GameObject does not change
Physics stuff doesn't run every frame, only on frames when physics are simulated
you'd have to explain exactly what you're trying to do
to get a better suggestion on what to do
which gameobject's size are you expecting to change?
Have you attached this script to some object?
which object's size are you looking at?
Is Time Scale being changed?
(looks like it is)
normally the text grows and escalates indefinitely
Can you answer my clarifying questions?
It will really help solve your issues
you are at the start of a long journey
keep it up!
yes
the name for what you are doing is a tween
the size of the gameObject
those are not yes or no questions (except the first one)
contain texet
if you have some animation knowledge
Hello, I'm curently creating a simple hit detection script that would be on the sword of my character (which has a box collider 2D). I wanted to know how it is possible to access to the script of the hit element (without the GetComponent<>() function which isn't working because I have severals enemy scripts) ?
you are tweening a pulse
because tweening is something people do all the time, there are lots of libraries that help you do this
one is called DOTween, if you want to tween in code
@pearl whale stay focused on what i'm talking about for a sec. the thing you want to do is called a "Punch Scale" by DOTween. look at http://dotween.demigiant.com/documentation.php and search the page for DOPunchScale
DOTween is the evolution of HOTween, a Unity Tween Engine
you can also do this using the built in unity animation tools.
it's worth learning how a dope sheet works too!
@pearl whale
while this isn't exactly what you're doing, you can modify the parameters to do this thing you are trying to do
don't say that' snot exactly what it is
i know what you wrote
you have to try to use the more general thing to get what you want
In other script timeScal set to 0.1f
don't mess with time scale at all
part 2 is, to deal with "pressing" on stuff, look up Event System
there is a great tutorial on EventSystem and UGUI on raywenderlich (now known as kodeco)
good luck!!
thx
When creating a script from Visual Studio, a namespace will be generated for it. Anyone know how to enable this behaviour when creating a script from Unity?
Hey, I am creating a fps view game and I want to add controller controls but the joystick Y Axis does not work. Is that normal ?
you can change the root namespace in project settings
just open up project settings and search for namespace
Yeah, but I realized this will put every script under this namespace. If I want to have a script in my Scripts/TestFolder folder, i would want it to have Scripts.TestFolder as namespace, just how visual studio does it.
With your example it will only be RootNamespace as namespace
to be honest, I would just add to that root namespace - although I typically create my scripts in rider for this exact problem. if you really wanted to, there are ways to get what you want
https://stackoverflow.com/questions/64214665/automatically-add-namespace-to-unity-c-sharp-script may be useful
but its just a lot of fuss for something that ultimately is done for free through your ide
Yeah but when making over 100+ classes I would rather have it automated 😄 Thanks for the help though
don't blame you. if you give it a go, please do @ me on how it goes. i've always been too lazy to do it myself
making over 100+ classes
❓
Why the question mark? 🙂
why use 100 classes when 1 big one does the job?
/s
Sort-of works, but the first letter of the first namespace dissapears for some reason haha
generally speaking, is having two command patterns in a single project messy code? Im asking as I am thinking of implementing a command pattern for actions to perform, and a command pattern for the state machines that activate them. is this messy?
If you really wanted to, you could build your own system with the AssetPostProcessor: https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html
Then check if the asset imported/creeated is a script file, and use System.IO to get the folder path (or string-split the params of OnPostprocessAllAssets for example), then you can use AssetDatabase to re-import the script, or you can make a custom Editor window to create new scripts from and set a namespace before your window creates the asset file - though both approaches would require Editor scripting and probably take time to setup correctly, just options you could explore
lol i just don't know yet what you're trying to do
i was scanning around
Just trying to make Unity generate namespaces for me automatically when i create a script
Thanks! I'll look into it
Rider does this for me
👀
based on the folder structure
do you use Resharper?
Only at work
Maybe I should install this here
But would reshaper solve my particular problem? 😄
this is what I said @slow trout, but you mentioned looking for a solution that does this when you create the script in unity right?
Exactly
Im trying to make the door open when I hit F but if i do it then the Door Opens and closes at the same time (can someone pls help)
`void Update()
{
RaycastHit hit;
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, InteractRange)) {
if(hit.transform.tag == "door")
{
Debug.Log("Raycast hit the Door!");
if(!DoorIsOpen)
{
if (Input.GetKeyDown(KeyCode.F))
{
animator.SetBool("DoorIsOpen", true);
DoorIsOpen = true;
Debug.Log("pressed F Door is now Open!");
}
}
if(DoorIsOpen)
{
if (Input.GetKeyDown(KeyCode.F))
{
animator.SetBool("DoorIsOpen", false);
DoorIsOpen = false;
Debug.Log("pressed F Door is now Closed!");
}
}
}
}
}`
i think there's a script template
@slow trout https://support.unity.com/hc/en-us/articles/210223733-How-to-customize-Unity-script-templates
Symptoms:
When I create a new script, the Unity Editor generates its content. For C# scripts, it uses the file name as the class name.
Cause:
Script templates are stored in %EDITOR_PATH%\Data...
I just solved it by naming my OG namespace starting with a _. I'm ok with the solution.
hope this helps
Thanks, that's what im using 😄
this is for when you screate it in unity
need some code advice here, not sure if ive found a really smart thing or im building a time bomb
// MoveStyles (a base class)
public abstract void Jump();
protected virtual void PerformJump(float f)
// Classic (a move style)
[SerializeField] private float m_JumpForce = 8;
public override void Jump() => base.PerformJump(m_JumpForce);
// Grounded state
Player.MoveStyles.Jump();
this is so i can add variables to the derived classes without inheriting them or overriding them in any way, just overriding the way that the base class gets ahold of them
is this brilliant or awful
this is awesome. i vaguely remember hearing about it somewhere in the distant past, but never bothered to dig in to it
Well, you're overriding Jump and could just opt to not have PerformJump but simply implement Jump instead 
but then i cant pass variables down from a derived class unless that variable is part of the base class itself
not without exposing those variables to other aspects of the code, that is
What do you mean? You'd just implement the function.. no passing necessary.
i ask the player's moveStyle to apply air friction, the style itself has its own variables that the base class - MoveStyle - does not contain
Right. What about it?
if i implement the function, i cannot pass the variable down, since the state machine deals with moveStyle, not with the specific derived styles
Removing PerformJump from the equation and you'd be able to apply whatever variable/functionality you'd want to the Jump function.
I'm not understanding what you're saying as the child overrides the behavior of the parent.
it does, but m_JumpForce is specific to "Classic"
Sounds like a very specific design.
then what would you suggest for a more flat approach?
i did have jump seperated for a while but i ended up repeating code between a lot of things and it got silly
Not sure but I don't see it bringing anything new to the table other than an intermediate
ay thats a little bit of a pickle
It sounds like you are avoiding a language feature in exchange for something that doesn't provide obvious advantage, at least that two other people can't see
its not that i was avoiding the feature, its just that i didnt know of a clean way to get that hooked to a state machine so i skirted it
now im realizing i went the wrong way and ive got to untangle it, not sure what the best way to do that is
My favorite approach is ripping the entire thing apart and asking myself why in gods name I did it this way
yup that sounds like the right way
Sometimes I try to decouple things way too much as if I'm writing enterprise software that needs to be maintained for 10+ years, that my input system isn't robust enough until I could conceivably plug a Wii balance board into my FPS control system
Yeah I'm realizing that modularity is a feature of unity as a whole
I need not implement more
In fact now I realize that modularity is as simple as just having overloads jfc
I make a lot of use of GetComponent respecting inheritance and what that lets you piece together
Oh so that's interesting
So you can grab parent classes and interfaces with it, and implement their own unique behaviors and inspectors
Yeah I always forget I can do that
i have a collision-based flag in LateUpdate that should get initialized by code executed in OnTriggerStay, and according to the unity docs on the order of execution, OnTriggerXXX gets called first beforeLateUpdate. however, during playmode, the the script is behaving as if LateUpdate gets called first before OnTriggerStay, resulting in the flag not getting initialized before LateUpdate code executed. this behavior occurs inconsistently between entering playmode, where the flag sometimes gets initialized by OnTriggerStay before its used by LateUpdate, and sometimes it doesn't. any ideas as to how to resolve this issue??
i want to spawn buildings, check if its colliding with any other buildings. if it is, rotate the building and disable its collision when its not colliding. if after performing the rotations and its still colliding, delete the building.
i tried implementing this by having the building spawn and detect if its colliding with another building by using OnTriggerEnter and OnTriggerExit. if the building spawns and its colliding with building object, it sets a flag isColliding = true and rotates itself as a way to result in non-collision to call OnTriggerExit that sets isColliding = false . in LateUpdate, a flag allowCollisionCheck is set to false only when isColliding is false.isColliding is also false by default and relies on OnTriggerStay to initialize it to true. So essentially, if the building spawns and its colliding with another building, OnTriggerStay is suppose to "catch" that and set isColliding = true, and if its not colliding isColliding remains false. the issue i experience with LateUpdate sometimes behaving as if it gets executed before OnTriggerStay is that since isColliding is false by default, allowCollisionCheck is set to false even when it spawns and is colliding, also preventing it from rotating itself.
void LateUpdate()
{
//if not colliding, set meshes to visible
if (!isColliding && !isActive)
{
transform.GetChild(0).gameObject.SetActive(true);
isActive = true;
allowCollisionCheck = false;
}
}
void CheckCollision()
{
if (isColliding && portList.Count > 1)
{
//remove previous port from list
portList.RemoveAt(0);
//recalculate rotation and offset position of node
Vector3 nodeEntranceOffsetPos = GenerateNode.CalculateNodeEntranceOffset(gameObject, edge.edgeExit);
transform.position = edge.edgeExit.position + nodeEntranceOffsetPos;
}
}
private void OnTriggerStay(Collider other)
{
if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
{
isColliding = true;
CheckCollision();
}
}
private void OnTriggerExit(Collider other)
{
if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
{
isColliding = false;
CheckCollision();
}
}
Place some logs and see what's really going on.
Pretty sure it's simply some misunderstanding and that everything's actually going correctly in order other than conditions not being true.
Reminder that LateUpdate can occur more frequently than Physics events. cs LateUpdate LateUpdate OnTriggerStay - event occurred, is colliding and shift position OnTriggerExit - nothing happened yet this frame even though the object was moved LateUpdate - disabled checking LateUpdate LateUpdate OnTriggerStay - event occurred, not allowed to check OnTriggerExit - event occurred, not allowed to checkOr it could be that events occur together well before a LateUpdate frame.cs LateUpdate OnTriggerStay - event occurred, is colliding and shift position OnTriggerExit - nothing happened yet this frame even though the object was moved OnTriggerStay OnTriggerExit - event occurred, is not colliding and shift position LateUpdate - disabled checking
i thought OnTriggerStay should get called before LateUpate, according to unity docs on order of execution
i did not account for that LateUpdate could occur more frequently and that was my misunderstanding, so the order of execution does not matter then?
the debug log shows:
LateUpdate
LateUpdate - disabled checking
LateUpdate
LateUpdate
LateUpdate
LateUpdate
.
.
.
and OnTriggerStay never gets called as a result
the intended order should be:
OnTriggerStay - isColliding
CheckCollision - shift position
OnTriggerExit - is not colliding
LateUpdate - disabled checking
LateUpdate
LateUpdate
LateUpdate
.
.
.
It runs in the physics loop in sync with FixedUpdate, not Update or LateUpdate
So when I compile a bunch of unity CS files into a DLL, all of the monobehaviour classes will still be accessible as components right?
i understand physic loop is in sync with FixedUpdate, my point is that OnTriggerStay (physic loop) should get called before LateUpdate (game logic loop) as a collision-based flag in LateUpdate relies on OnTriggerStay to initialize it before running LateUpdate code. yet, the debug shows that LateUpdate is getting called before OnTriggerStay
His point is, that it shouldn't happen at all after lateupdate. The actual physics engine gets stepped before lateupdate
So unless you're stepping it manually using Physics.Simulate(), then it likely isn't getting called after lateupdate
And you might just be overlooking something
Maybe show the functions with logs and the console logs.
Hey everyone. Can someone explain this to me? I'm getting an error while executing the code in editor. The error:
void LateUpdate()
{
Debug.Log("LateUpdate");
//if not colliding, set meshes to visible
if (!isColliding && !isActive)
{
Debug.Log("LateUpdate - disabled checking");
transform.GetChild(0).gameObject.SetActive(true);
isActive = true;
allowCollisionCheck = false;
}
}
void CheckCollision()
{
if (isColliding && portList.Count > 1)
{
Debug.Log("CheckCollision - shift position");
//remove previous port from list
portList.RemoveAt(0);
//recalculate rotation and offset position of node
Vector3 nodeEntranceOffsetPos = GenerateNode.CalculateNodeEntranceOffset(gameObject, edge.edgeExit);
transform.position = edge.edgeExit.position + nodeEntranceOffsetPos;
}
}
private void OnTriggerStay(Collider other)
{
if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
{
Debug.Log("OnTriggerStay - is colliding");
isColliding = true;
CheckCollision();
}
}
private void OnTriggerExit(Collider other)
{
if (allowCollisionCheck && other.gameObject.CompareTag("Node"))
{
Debug.Log("OnTriggerExit - is not colliding");
isColliding = false;
}
}
The code:
if (template.IsNullOrWhitespace()) { var newscene = EditorSceneManager.CreateScene(scenePath); EditorSceneManager.SaveScene(newscene, scenePath); EditorSceneManager.CloseScene(newscene, true); }
What is the value of isColliding and isActive on initial run?
LateUpdate can occur before any Trigger is made if you simply start the object on top of the event trigger as Physics events do not occur every frame.
im not sure what you mean by "His point is, that it [OnTriggerStay] shouldn't happen at all after lateupdate". im not in disagreement with that. i want OnTriggerStay to get called before LateUpdate
--Start of application--
LateUpdate
LateUpdate
LateUpdate
LateUpdate
LateUpdate
OnTriggerXXX
LateUpdate
LateUpdate```
isColliding is false and isActive is false on intial run
It would immediately disable allowCollisionCheck and no further physics messages would occur.
Physics step would attempt to occur first, if and only if the physics frame should occur.
Which would be at about 50 frames per second by default.
Or something of the sort.
Whereas maybe you might be getting 200+ fps on the main loop (Update and whatnot)
Loop:
fixDeltaS += deltaTime;
RegDeltaS += deltaTime;
while(fixDeltaS > fixRate)//Occurs first but only if the elapsed time has passed - fixed rate
Do physics stuff
fixDeltaS -= fixRate
Do Update and everything else every frame.```
Hello, I'm using the Steam API and I'm having a problem inviting players.
First, I'm creating a lobby with Steamworks NET. Then, if the lobby is formed, I send a data to the lobby. Then I invite someone using the Steam interface. But when the other party accepts the request, nothing happens. I'm listening to all "GameLobbyJoinRequested_t" and "LobbyEnter_t" callbacks and printing with Debug.Log. But there is never any result.
right, i understand now that LateUpdate can still occur before Trigger. but i need physics step to occur first, in order to call OnTriggerStay before LateUpdate when i begin playmode. how would i resolve this issue? or is there a suggestion for different implementation?
As the error says, use NewScene, not CreateScene
If you aren't in play mode
🤷♂️ Time.time > Time.fixedDeltaTime (one frame)
It would be dirty to have a one time check. Could perhaps do so with a coroutine as well
Oh, ok. Didn't notice that. Thank you! That helped
Coroutine:
yield return new WaitForFixedUpdate();
while(true)
do stuff for the remainder of the application
yield return new WaitForEndOfFrame();```
Or if that's dirty, you could inject some function into an action and call it during LateUpdate after the first frame.
IEnumerator Start:
yield return new WaitForFixedUpdate();
DoStuffAfterOneFixedFrame = stuff;
LateUpdate:
DoStuffAfterOneFixedFrame?.Invoke();```
Consider caching yields though if they aren't one time calls.
Or just have the script inactive for a set duration of time (or till one fixed update has occurred) then enabled it - would require the usage of a manager. cs public MonoBehaviour activateLater; IEnumerator Start: yield return new WaitForFixedUpdate(); activateLater.enabled = true; this.enabled = false;
Many ways to go about this.
Reminder that a coroutine would be disabled once the component becomes disabled or object inactive.
Another script observing this script would be require for the last suggestion made and decoupling the physics interaction with late update interaction - you'd probably want the physics stuff to still be able to have occurred.
is it camel case?
It's the c# style guide . . .
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
alright thanks
also I get this is just a warning but how could I make it "efficient"?
Should be able to right click and apply suggestion.
new Vector3(x, 0, z) * (Time.deltaTime * 10);
this is the solution it gives, isn't this not correct?
Ideally scalars should be operated upon first then applied to a Vector
shouldnt deltatime be multipled after or does it not matter
Looks correct and goes according to the guidelines pinned in #💻┃code-beginner
thanks for the coroutine method, i understood this as: implement a coroutine to wait for FixedUpdate to allow for OnTriggerStay to get called first before LateUpdate. then i realized i didnt need LateUpdate, but could instead run the code that was in LateUpdate, in the coroutine instead. and then have the coroutine call itself as needed if collision is still detected. https://gdl.space/efihajahar.cpp
It doesn't matter as long as the scalars are multiplied with each other before multiplying with the Vector3
each time you multiply the Vector3 by a float it has to multiply each axis of the vector individually which means that's 3 multiplications right there. by mutliplying your floats together first then multiplying that by the Vector3 it only has to do 4 total mutliplications and doesn't have to create new Vector3s more than once
Did not look but sounds completely valid.
makes sense, thanks
ie this one right here most likely
Consider not Starting a lot of Coroutines often though. It's fine to have them running throughout the entire life of the application but starting them does have some initial costs. Also cache yield instructions if possible.
i see. im reading more on this and other garbage collection tips
thx ^^
Hey guys, sorry for duplicate question but I couldn't seem to find an answer in #💻┃code-beginner. I seem to be having some trouble with Quaternion.FromToRotation. I'm making a tank turret type thing where I control the guns elevation and the turret rings rotation separately, and as you can see here while the guns elevation IS correctly facing the target, the turret rings rotation is however not. Here is the code I wrote:
{
newQuat = Quaternion.FromToRotation(transform.up, (targTransf.position - transform.position).normalized);
Debug.Log(newQuat.eulerAngles);
Debug.DrawRay(transform.position, newQuat * Vector3.forward);
setRot(newQuat.eulerAngles.y, newQuat.eulerAngles.x);
}
private void setRot(float x, float y)
{
gunBase.localRotation = Quaternion.Euler(0, x, 0);
gunBarrel.localRotation = Quaternion.Euler(y, 0, 0);
}
The issue seems to be with "newQuat" and Quaternion.FromToRotation, as debug.log shows that the eulerangle is correctly adjusting along the Y axis, however the x axis is just not changing, with its value never exceeding a value of 24-ish. Does anyone know what might be up? I can't find much tutorials involving Quaternion.FromToRotation at all, and from what I've read there shouldn't be any reason its not returning the correct "horizontal" value... unless maybe I'm understanding the way it works incorrectly? I was wondering if .FromToRotation accounts for the z axis but I dont see why it wouldn't... any help is really appreciated regardless.
hey question,
im making a mod for a game (dw it supports modding)
and i want to add pathfinding to a object, i have it so the object can move towards a player normally using Vector3.MoveTowards but obviously it doesnt detect objects stopping it
i want to know if there is any pathfinding solutions that can work in runtime without baking or placing nodes and work dynamically as objects might be places in it way
preferably i would like to avoid adding components to the floor such as navmeshsurface as i dont know the name of the floor
not sure if it makes sense
im making a goose in a game follow people if you are interested, usually the goose is just a object you can pickup but i wanna make it able to move around the world even though i didnt make the world
im not fully sure of the untiy engine version but its old
2019.4.xxf1 or something
I mean if you want "pathfinding" in unity ur gonna need a navmesh
figured
and a navmeshagent
was just wondering if there was alternatives out there but nvm ig xD
does anyone here have experience with the pixel crushers dialogue system plugin?
don't crosspost
mb
I'm making a top down 2D mini-golf game for fun, what would be the best way to 1. have the ball bounce off walls like it should (without just sliding against the wall) and 2. have a sort of friction (I have a rigidbody2D but its top down so it doesnt do much
Hello everyone 😁
I just wanted to ask something very general, tell me if I'm in the wrong channel
is it bad practice to have multiple scripts on one GameObject, all toggled on/off by a single, larger controller script?
all of my scripts use Update calls so I prefer to avoid them all running at once
I dont think so I do it
So I need to use navmesh
But im using it in a mod won't needs to be runtime so I can't bake anything it
I'm also using a older version of unity 2019
Is there a way to have the agent find a usable surface? I have the names of the floor objects but I can't manage to assign then a navmesh for the agent also going bed now so if you have an answer please @ me thx
I'm having a hard time grasping why 5 % 6 (as an example) evaluates as 5. I understand the modulo operator when the first parameter is larger. Like it makes sense to me that 6 % 5 evaluates as 1, since 5 "fits" into 6, with 1 remaining. But I'm just not understanding the mathematics behind it when the first parameter is smaller. If someone would be able to explain it to me, I'd be very grateful.
it's just a remainder operator. did you ever learn long division in grade school?
it's the same concept as a remainder in that
5 cannot be evenly divided by 6, so the result of the division is 0 with a remainder of 5
ahh, thanks. that made it click for me.
Anyone know how to convert int to generic Enum?
In known Enum, you can go like this:
(MyEnum)index
But on generics, I can't.
Class<T> where T : struct, Enum
(T)index //Error
the enum needs to be a concrete type you cast to
whats the difference between
public Foo FooManager => FindObjectOfType<Foo>();
And
Awake(){
FooManager = FindObjectOfType<Foo>();
}
Is there a negative between using the first?
with the first one every time you access FooManager its doing the find, with the 2nd its doing it in awake then you are accessing the already found one
I see and
private bar
public Foo FooManager
{
get => bar
}
And
Awake(){
bar= FindObjectOfType<Foo>();
}
in this case FooManager will get the reference to bar right?
So basically something like
private ToggleAndFadeUIObject _toggleAndFadeUIObject => GetComponent<ToggleAndFadeUIObject>();
is bad practice because it calls the GetComponent everytime
Thanks for the help!
yes
generally would avoid it in 1 of 2 ways, just click and drag the reference in directly
or do the GetComponent in awake
and just expose it publically later with a getter
you can also avoid the backing field in this case you want
public Foo FooManager {get; private set;}
then you can set it in Awake
but things can still publically read it but not set it
Gotcha thank you!
public Foo FooManager {get; private set;}
private void Awake(){
FooManager = FindObjectOfType<Foo>();
}
was so hoping it was just a quicker syntax to lambda it 😄
the lambda syntax is the same as if it was a function
well better wording is getters and setters are just functions disguised as a field, the logic in both of them runs when accessed not at initialization
I tried to use a Physics material 2D but it didnt work with either, it made it bounce a little but sometimes it would break and bounce back the direction it came
Anyone got tips for readably getting the corners of a square? I'm a master of overthinking practicing my craft.
Attempt 1:
corners[1] = new Vector2(posX + sideLength / 2, posY + sideLength / 2); // Top Right
corners[2] = new Vector2(posX + sideLength / 2, posY - sideLength / 2); // Bottom Right
corners[3] = new Vector2(posX - sideLength / 2, posY - sideLength / 2); // Bottom Left```
Attempt 2:
```string[] cornerDirection = new string[4] { "-+", "++", "+-", "--" }; // Starting in top left, continues clockwise
Vector2[] corners = new Vector2[4];
for(var i = 0; i < sideLength; i++)
{
float sideX = 0f;
float sideY = 0f;
if (cornerDirection[i][1] == '-')
sideX = posX - (sideLength / 2);
else if (cornerDirection[i][1] == '+')
sideX = posX + (sideLength / 2);
if (cornerDirection[i][2] == '-')
sideY = posY - (sideLength / 2);
else if (cornerDirection[i][1] == '+')
sideY = posY + (sideLength / 2);
corners[i] = new Vector2(sideX, sideY);
}```
I'm sure there's a smarter way of doing this that I'm just not seeing
what's wrong with option 1? don't be clever, make it readable
option 1 has some math issues (check your signs 😉 ) but is otherwise fine
ah wait, looks like you may have edited the issues i was referring to
yup, I had forgot to finish that part, I'm kind of proud of the janky mess that is the second script (although I obviously won't be using it)
It just feels wrong having four nearly identical lines in a row
alternatively, you could store (1,1),(-1,-1),(-1,1),and(1,-1) in an array then loop over that array and multiply that by the half extents
ooh that's not a half bad idea
and sounds much more readable
(and harder to mess up the signs for)
did you restart after installing it?
Let me try
This seems much better, thanks!
int[,] cornerDirection = {{-1, 1},{1, 1},{1, -1},{-1, -1}}; // Starts in top left, continues clockwise
for (var i = 0; i < 4; i++)
{
corners[i].x = posX + sideLength * cornerDirection[i, 0] * 0.5f;
corners[i].y = posY + sideLength * cornerDirection[i, 1] * 0.5f;
}```
Still gives error
Is there anyway to cut down on code for a variable kind fighting system?
like if you're in the air vs if you have the enemy grabbed
Im thinking like state machines could do this but I'd like to know if theres any other ways
animation state machine XD
but it would be a pain to debug I think
I am not really sure if this is beginner, general or advanced but feels like it is more general. I have a unity scene with mapbox and a api from where I get coordinates. I make the coordinates into unity world positions and place the green markers where they are. I now want to create "links" between the points by using cylinders. I first tried to use the linerenderer but it was buggy (only showing from certain viewing angles) and preformance was bad. I have tried a couple of things but can't really figure out how to calulate the rotation and scale for the length. The cylinder prefab is in a empty object wrapper that makes it lay down on the side, and raises it up as well as setting the origin to the end of the cylinder.
var pPos = _map.GeoToWorldPosition(p.Prev.Pos, true);
var vec = (pPos - pos).normalized;
linker.transform.rotation = Quaternion.LookRotation(vec);
linker.transform.localScale = new Vector3(vec.magnitude, 1, 1);
prefab model where the origin is shown
The Z axis is generally the forward axis in Unity, you should rotate the 3D mesh itself so that its z is facing forward (instead of the current X axis which is generally right)
And use Z scale instead of X
Alternatively you can do what you currently do but apply some corrective rotation afterwards with transform.Rotate for example.
Alright, will do that, thank you :)
like this?
the direction works now, thank you but I think my scale calculation is wrong.
I removed the .normalized because with it the size only got the be 1
B-A = the offset between two vector points
Grab the magnitude of this offset, which is the length
Set the cylinder length with that
There shouldn't really be any more to it
If that doesn't work, check if your cylinder model is "one unity meter", by comparing it to a cube
var pPos = _map.GeoToWorldPosition(p.Prev.Pos, true);
var vec = pPos - pos;
linker.transform.rotation = Quaternion.LookRotation(vec);
linker.transform.localScale = new Vector3(1, 1, vec.magnitude);
so this should work?
It looks alright from a quick glance, can't you test it?
this is the result, not quite right
should the cylinder be the same size as the cube?
but I have never modified the cyilders scale, is the cylinder by default "longer"?
Yes
I got to go tho
Gl
@earnest epoch hey, i still have been working on that i figured something but it doesnt work well. What i did is create a method and make it menu item. what method is do change a bool. so i press start from loading screen menu item it changes a bool to true in datamanager (static class, player prefs). but theres a thing when i change that bool to true and press play it does not start from loading scene, but when i stopped playing and press play again it starts from loading scene. in short player prefs bool work after first play and i dont know why
got it working, thanks to all of you who helped me!
Does anyone know why I'm getting different timings on my Debug.Logs for this code?
foreach (var spikeTrap in Globals.Instance.spikeTrapList) {
spikeTrap.InitializeTrap();
}
I'm calling this during the Start() function of my game manager script. spikeTrap.InitializeTrap() simply displays a Debug.Log message saying that it started. For some reason I'm getting different timings on these messages though... Shouldn't they all happen in the same frame?
yep, unless you are calling it multiple times from other places at other times and not realizing it?
What are you logging? Even if things happen in the same frame that doesn't mean they happen at the same time
Long story short, I have timers that repeat once every 10 seconds, causing these Spike traps to activate. The problem is that some of the traps aren't in sync with the others. They're literally all running at the same exact time though so I'm lost...
I think it mostly depends on how you made the timer
Is it a coroutine?
either they aren't in sync, or they are running at the exact same time, but both are certainly not true so you should figure out which one
not much we can do for you though
add a lot of very verbose logging or step through with your debugger and make sure the code is being run like you think it is (cause it isn't)
I'm using a custom timer class, I'll try to see if one single timer managing all of them at once will help. Regardless, they start at different times despite only relying on the Start() method for the initialization process.
do you have objects coming alive later than others?
start is just for that monobehavior but if you don't instantiate it until later, it won't run start until then
They're all preplaced in the scene
But I am instantiating other objects at the same time
Yes but how is this timer implemented
My point is that using a coroutine for it is unreliable
So if each trap uses their own timer instance they are not guaranteed to run at the same speed
Because yield return new WaitForSeconds(5) for example will never wait exactly 5 seconds
So if each trap has their own timer instance and it works with coroutines, that's atleast part of the problem
TLDR; "a custom timer class" unfortunately isn't super helpful in narrowing down the problem vs. talking about what that timer is rooted in.
It's not coroutine based but maybe it shares the same issue:
private void Update() {
for (int i = 0; i < timerList.Count; i++) {
timerList[i].UpdateTimer();
}
}
^ That's part of a single TimerManager class which contains a List of Timer objects. Each Timer does this:
public void UpdateTimer() {
if (isPaused) { return; }
timeElapsed += Time.deltaTime;
if (timeElapsed >= timeNeeded) {
if (isRepeating) {
callbackAction.Invoke();
timeElapsed = 0;
} else {
callbackAction.Invoke();
Cancel();
}
}
}
Ok this is fine because this is exactly how a timer should be
Because unlike a coroutine's instruction, time.DeltaTime is very reliable
Atleast we can narrow the problem down
well do you ever pause any of em?
Nope
All traps have callbacks registered, which is where they do their thing? Or does a central manager have a callback registered which in turn asks each trap to do their thing?
Currently I've given each trap it's own Timer with it's own callback
But I'm about to test one single Timer to manage all of them
I still don't understand why they'd be out of sync from the start though... I'm not even using the Timers there
If you spawn the traps in update.
Or otherwise have them register there.
That would run the risk of having the timer for a given trap run one frame early or late vs. others.
does a scene in unity contain modification or just a change in the objects?
so if saved a scene, and then I modified the scripts, I assume the scene that I saved before will contain the new code
right?
Scripts are not stored in scenes, no. However changed serialised values are.
So if you serialise value A with a default value of 5 specified in script, change the value to 7 in the inspector of an object in the scene, and then change the default value in script to 14 then the value in the scene will still be 7.
Same holds true for instances on prefabs ofc.
Default values for non-serialised variables do not stick in the same way. If B is a non-serialised variable on the same script with a default value of 5, you then add an instance to a GO in a scene and change the script default value from 5 to 14, then the value will be 14.
yeah, that I made the right call,
I was trying to disable sound, and the project is like 50 GB so I did not want to be stabbed back when I do the changes and somehow the scenes did enable them back, so I disabled them in the scripts.
Thanks
No problem 🙂 Worth noting that if you're running without sound for personal preference, it is worthwhile deciding on one day per week or so being your sound-on day. Many, many projects have slid because people developed without sound and then discovered an ocean of audio issues just before some milestone - when they finally turned it back on 😉
Hello, how is it possible to access to the script of a GameObject with a variable name (because I have severals enemies with their own script) ?
Do you spawn those enemies using a script, or do they already exist in the scene?
they already exist
If you only need to reference a single enemy, you could just assign them to a [SerializeField] private Enemy _enemy; field. Alternatively have a manager keep track of your enemies by having it collect all existing enemies when your game starts, and continue filling/removing from that list when you add/remove enemies in your scene. You then just iterate that list.
Shitty solution is using any of Unity's find methods, which I do not recommend.
ok thanks
Hello. How to make a BoxCast in 3d world with ui element, like image? I know about raycast with (Camera.main.ScreenPointToRay(Input.mousePosition)), so I do have the position and direction. Now I need to make my cast the same size as ui element, any ideas how to do that?
So, basically, I want to drag an image on the screen and get all 3D objects that behind it.
Is it technically impossible to have all vertices in a mesh be unique? what I mean is, a cube consists of 8 vertices, but technically a generic unity's cube is using 24 vertices. So each quad is using its own set of vertices. is it possible to make it use 8 vertices? and if yes, is it applicable to more complex meshes?
for example, I create a mesh that contains 16x16 quads (looks like a plane), and if all vertices were unique, it would use only 289 (17*17) vertices, while in fact its using about 1500
In unity I have a mapbox 3d map and when I am zoomed out alot where a city is pretty much covered by a small area I don't need it to render every single point I have there. Is there some efficient way to deactiave 3d objects (prefabs) that have the same positions or the positions are very close, lets says within 0.1 unitys of each other?
Yes, triangles can share vertices. The problem with that is a vertex can only have one normal. So if you start sharing vertices in a cube, you can't have the vertex normals point where you need them to.
hey guys
so i have a vector3 which has only its X and Z set, Y is set to 0
i use this vector for velocity
but i need to get the direction from this vector
so i need to get Y
But this is only necessary for sharp edges. For smooth, rounded edges, the vertices can be shared without problems.
it is against the rules to crosspost, delete it
so the answer is, 24 vertices in a cube is the least number technically possible? right?
If you want correct normals for the faces, yes.
alright, got it
But technically you could also calculate the normals in the shader manually or encode the three normals into other vertex attributes and unpack them in the shader.
I may not need correct normals in some cases?
Hey guys! I have a UI popup containing 9 buttons, and I have this initial foreach loop in void Start() that basically says “wait until the button is clicked” by adding a listener (Screenshot 1). This is handled by HandleButtonClick(). Here, whenever the button is clicked, I have the bool buttonIsClicked set to true (screenshot 2)
In a connected script that references this script^^ (aka line 68), for some reason this isn’t being called/reached. I put Debug.Log’s, and only the outer “First if statement reached” is being printed, and not this inner one. I checked that the buttonIsClicked bool is true, which should progress to this inner one.
Any feedback/comments would be greatly appreciated!
Not necessarily. Not for unlit shaders, for example.
thanks!
guys how to set default value for struct like Vector3 in a public method like this?
public static void MyMethod(this CharacterController controller, Vector3 offset = new Vector3(-.5f, 0, -.5f)) // This will give error "Default parameter value for must be a compile-time constant"
I can only set it with new Vector3() or default. Maybe there's some trick?
well, you've narrowed it down pretty well - there's pretty much only one thing it can be if all of that is accurate, your GetComponent call isn't getting the right component
is there a way to cast a Scene as SceneAsset
(SceneAsset)EditorSceneManager.GetSceneByBuildIndex(0)
this is what i want to achieve
i think there s no way
ahhahahah 😄
static EnterPlayModeSceneChange()
{
SceneAsset loadingScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(loadingScenePath);
if (loadingScene == null)
{
Debug.LogWarning("There is no LoadingScene or not found!");
EditorSceneManager.playModeStartScene =
AssetDatabase.LoadAssetAtPath<SceneAsset>(EditorSceneManager.GetActiveScene().path);
return;
}
EditorSceneManager.playModeStartScene = loadingScene;
}```
my co worker said you can do this better instead of getting asset in assetdatabase so i gave it a try but
i have no idea how to make this better
thanks for your response! i'm trying a different approach. Instead of calling the StartCoroutine under line 72 in the second script (called InterfacePivot.cs), I thought maybe it has something to do with the "ordering" of when these methods might be called. When my gameobject is instantiated, it is immediately tagged with "TaggedSelectionInterfaceInstance"
In my first script (called SelectionInterface.cs), I find that instantiated gameobject by tag. However, I'm getting a 'Object reference not set to an instance of the object.' on line 154
I've previously defined interfaceScriptInstance in the third screenshot here, so I'm not quite sure where I went wrong.
I'd avoid using FindGameObjectWithTag entirely
hmm gotcha, what other alternatives would there be? quick google search says its bad for performance, but realistically im not too worried about that
it's not clear to me why you're mixing buttons and triggers here, what are you trying to do?
Do not ping anyone into your question. #📖┃code-of-conduct
So basically I'm around this environment. When I collide into this empty gameobject (with the InterfacePivot.cs script attached)... I instantiate this canvas/UI with these buttons. (with the SelectionInterface.cs script attached)
When I click any of these buttons (buttonIsClicked bool), I start this coroutine (AccessMeshRendererAndShowFeedback)
right.. but you're checking for whether the button is pressed immediately in OnTriggerEnter? that will of course be false
Ohh i thought it would wait according to my AddListener on my buttons, which I added in void Start in SelectionInterface.cs (screenshot 1)
But would that(?) be a separate issue than the one I'm experiencing now, aka the object reference not being set to an instance
OnTriggerEnter wont pause in the middle of its execution and wait for a button to be pressed
Hmm i see i see, so in that case should I basically remove the line in my InterfacePivot script that checks if the button is clicked immediately OnTriggerEnter, and instead go with this "new" route (that for some reason gives the object reference error)?
if you're essentially instantiating a prefab that contains your buttons and interface script, you can set them up with references in the inspector directly
alternatively GetComponent will work, but you need to make sure it's on the right object in your hierarchy
Any idea how to make a tictactoe game, without wasting a bunch of space with a very larger number of if statements?
(Player vs AI)
so coming here again for my path-finding stuff,i am looking for help again,to try to optimise the amount of nodes to be searched,I tried doing a simple calculation which worked perfectly in another try,now i am trying to apply it to grid generation,but it gives an InvalidOperation Error (ArgumentRange error when burst compilied),any idea why?
//Doesn't work in a backwards way
Vector2Int gridSizeVector = Vector2Int.CeilToInt(endPosition - startPosition) * 2;
int2 gridSize = new int2(gridSizeVector.x, gridSizeVector.y);
//Works in a backwards way,but sometimes bugs out
int2 gridSize2 = Mathf.RoundToInt(Vector2.Distance(startPosition,endPosition)) * 2;
the grid creation stuff
int2 GetInt2FromVector2(Vector2 position)
{
int x = Mathf.FloorToInt((((position - startPosition).x) + ((gridSize.x / 2f)) / offset));
int y = Mathf.FloorToInt((((position - startPosition).y) + ((gridSize.y / 2f)) / offset));
return new int2(x,y);
}
the stuff that converts from world to grid
- try to use the mathmatics package instead of Mathf (not your issue but is optimised for burst) e.g:
math.floorToInt()
it's okay,this part isn't in the job
Whats the exact burst error? And show the code which the error says it can't compile
should have specificed that
it's a bit big so i am uploading it to a text hosting site
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.
Can you show the PathFinding.PathFindJob
and if it's not burst compiled does the error give better info? (if it still happens)
https://pastebin.com/E3t8vy41 it's a bit big but okay
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.
i don't understand anything but here it is incase you need it
can you paste what Pathfinding.cs line 235 is on your end as the paste site as it at a } and i just want to make sure it isnt a formatting issue
In unity I have a mapbox 3d map and when I am zoomed out alot where a city is pretty much covered by a small area I don't need it to render every single point I have there. Is there some efficient way to deactiave 3d objects (prefabs) that have the same positions or the positions are very close, lets says within 0.1 unitys of each other?
path.Add(new int2(cameFromNode.x, cameFromNode.y));
i wonder if you have some sort of infinite loop and is then erroring due to memory limits
try adding a log to the while loop and count how many loops it's done?
var count = 0;
try
{
while (currentNode.cameFromNodeIndex != -1)
{
count++;
PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
path.Add(new int2(cameFromNode.x, cameFromNode.y));
currentNode = cameFromNode;
}
}
catch(Exception e)
{
Debug.LogError($"Looped {count} times!");
Debug.LogError(e.ToString());
}
something like that
it didn't work
thats strange, it should catch the throw on the error
uh, i guess you can just log the count each time in the while instead
var count = 0;
while (currentNode.cameFromNodeIndex != -1)
{
count++;
Debug.LogError($"Looped {count} times!");
PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
path.Add(new int2(cameFromNode.x, cameFromNode.y));
currentNode = cameFromNode;
}
but i am pretty sure this while loop just isnt stopping
ok
also i sorta found something that did somewhat work abit
i basically checked if the end node is smaller than 1 and made it so that it would act as the origin instead of the direction in the gridSize calculation
it's frozen for more than usual,is that okay?
yeah logging in the while will take a lot longer
thats why i wanted to avoid it with the try catch
if you open the editor log it should show some values
the editor is probably fully frozen so you'll need to path to it manually (or you can press a button next to the console to open it if it wasnt)
for windows it's: %LOCALAPPDATA%\Unity\Editor\Editor.log
in other new i think i've found your bug
you use this to calculate the end node index int endNodeIndex = CalculateIndex(endPosition.x, endPosition.y, gridSize.x);
but you are checking this in the while currentNode.cameFromNodeIndex != -1
it doesnt seem like the end node will be ever be -1?
i was following a tutorial,and it said that if the path is invalid,the end could be -1
yes, but the path is valid at this point
if (endNode.cameFromNodeIndex == -1)
{
//Couldn't find a path!
return new NativeList<int2>(Allocator.Temp);
}
you are doing this check before the while loop
what you want is this
while (currentNode.cameFromNodeIndex != endNode.index)
or maybe
while (currentNode.index != endNode.index)
probably that one
wait sorry
i forgot that this bit goes backwards when finding the path from the nodes
so you'd want to check for the starting position index
which in theory should have this be true currentNode.cameFromNodeIndex != -1
huh
i guess you could try sending in the starting index as a parameter (or the node) and checking that instead
while (currentNode.index != startingNode.index)```
here is the log editor file @lucid valley
can you see if you can update your collections package, then that {size} should be fixed
so i just replace endNode with startNode,but what else do i replace?
i am on the latest release for the collections package
private NativeList<int2> CalculatePath(NativeArray<PathNode> pathNodeArray, PathNode endNode, PathNode startNode)
{
if (endNode.cameFromNodeIndex == -1)
{
//Couldn't find a path!
return new NativeList<int2>(Allocator.Temp);
}
else
{
//Found a path
NativeList<int2> path = new NativeList<int2>(Allocator.Temp);
path.Add(new int2(endNode.x, endNode.y));
PathNode currentNode = endNode;
while (currentNode.index != startNode.index)
{
PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex];
path.Add(new int2(cameFromNode.x, cameFromNode.y));
currentNode = cameFromNode;
}
return path;
}
}
huh, guess DOTs is on a preview version of the collections package then as it's fixed in my project
don't unity version allow access for certain types of packages?
it became even more broken
@lucid valley also incase you didn't see
i'm not too sure what that meant
do you know how to use a debugger?
All i can suggest now is to use breakpoints and see whats happening during the loop
basically,this
if (endPosition.x >= 1 && endPosition.y >= 1)
{
var direction = endPosition - startPosition;
}
else
{
var direction = startPosition - endPosition;
}
ok
@lucid valley does this help?
yeah, path is massive
55428584 length
try making a small grid then inspect pathNodeArray and try to work out the path backwards yourself using the cameFromNodeIndex
Using the same logic the while uses
Hi everyone, I am looking into Unity Lobbys and I was wondering what is the correct way to set up a lobby in the sense that there doesn't need to be a specific host. By this I mean I would like for all players to just press a join button, and one of them automatically making a lobby that the others join seamlessly, without the need for a second seperate button for someone to click to host a game.
I've been reading the docs and they don't really seem to cover this, quick join is kind of what I want, however that doesn't seem to mention anything about creating a lobby if non are avaialbe. Would the solution be to have all players just create a lobby and search for one at the same time? Any pointers on what would be good practice would be apreacated
ok,but how?,the grid size depends on the distance
like just for debugging, just send in a small grid size, like a 3x3 and put the start and end points at the opposite corners
and follow the code through using breakpoints
so i tried 2 positions
one where the end position is positive,and another where it is negative
the negative one is the one that causes all the problems,but the postive one is working fine
your pathfinding code doesnt support negative coords (the grid is always positive, see the beginning of the Execute)
i guess you could say it is "normalised" to 0, 0
that case should've been caught as a no path found
i'm not sure how it's ending up to that while loop
yeah
you turn it back into your world coord after the path has been found using GetPositionFromInt2
but is there a way to make it so that the negative values can work?
yes
i guess that's what your offset is for?
actually thats just a float
humm
it is the offset between nodes
public Vector2[] FindPath(Vector2 startPosition, Vector2 endPosition, float offset)
{
int2 gridSize = Mathf.RoundToInt(Vector2.Distance(startPosition, endPosition)) * 2;
int2 gridOffset = int2.zero;
gridOffset.x = startPosition.x < 0 ? Mathf.CeilToInt(-startPosition.x) : 0;
gridOffset.x = endPosition.x < 0 && gridOffset.x > endPosition.x ? Mathf.CeilToInt(-endPosition.x) : gridOffset.x;
gridOffset.y = startPosition.y < 0 ? Mathf.CeilToInt(-startPosition.y) : 0;
gridOffset.y = endPosition.y < 0 && gridOffset.y > endPosition.y ? Mathf.CeilToInt(-endPosition.y) : gridOffset.y;
//Other logic
{
that should get you an offset so that the start and end are always in positive space
yeah,but won't the gridSize be the same on the x and y axis,making it basically counterpoint the whole point?
int2 GetInt2FromVector2(Vector2 position)
{
int x = Mathf.FloorToInt((((position - startPosition).x) / offset) + ((gridSize.x / 2f)));
int y = Mathf.FloorToInt((((position - startPosition).y) / offset) + ((gridSize.y / 2f)));
x += gridOffset.x
y += gridOffset.y
return new int2(x,y);
}
humm, Vector2.Distance will always be positive
You cant have negative distance
and then in this function you'll want to take away the grid offset
private float2 GetPositionFromInt2(int2 value)
{
return (new float2(value + origin) * offset) - ((gridSize.x / 2f) * offset);
}
so you'll need to send it into the job
this doesn't work,start position is a vector2 with floats
it's in the job
private float2 GetPositionFromInt2(int2 value, int2 gridOffset)
{
var position = (new float2(value + origin) * offset) - ((gridSize.x / 2f) * offset);
position.x -= gridOffset.x;
position.y -= gridOffset.y;
return position;
}
you mean the gridOffset?
uh make it a float2 then
yeah
then this doesn't work
should i cast,round or floor it?
ok, i went back to int2 and ceiled them (you might need to cast them after i can't remember if ceilToInt is weird and returns a float)
I'm trying to understand bitmask. I'm using EditorGUILayout.MaskField which gives me an int result. If I have a List<int> of different results, how can I use LINQ to get only the ones from the list that contain a specific string option?
there is no ceilToInt in the math class but there is a CeilToInt in the Mathf class
oh, its just called ceil
and you'll have to cast it to int after
or make an extension method to do it for you
or actually you can use the Mathf since this isnt bursted
@lucid valley it seems to somewhat work?
uh, did you do this bit?
yeah,but i just made the gridOffset as a variable rather than a parameter only value
public int2 gridSize;
public int2 startPosition;
public int2 endPosition;
public float2 origin;
public int2 gridOffset;
public float offset;
public bool canMoveDiagonal;
public NativeList<float2> resultPath;
basically put it here
@lucid valley it seems i forgot to assign it in the Job Constructor,but it still has the same result
Does anyone know how to make a character who moves using Vector based motion to not go flying off slopes? I want my character to stay on the floor and not go flying
search for a lobby, which would be saved somewhere i'm guessing, and if one doesn't exist, have the player be the host of a server
Assuming you are using a rigidbody + collider setup instead of a CharacterController component, you will want to apply a constant downward force to essentially act as gravity for your rigidbody - you can do the same with a CharacterController, theres just less flexibility as you only have 1 way of applying motion, and there may be some cases where going up-hill or something like a double-jump or swimming, etc that you may want to disable or reduce your gravity for - if you need help with movement, you could search up tutorials for a rigidbody based character controller, here is one good example: https://www.youtube.com/watch?v=1LtePgzeqjQ
In this tutorial, you will learn how to make a Rigidbody - based player controller using Unity's new input system.
Thanks, good idea
Is there a way to send a friend the game I build for IOS via e-mail or so? Do I need to publish it on the appstore?
u can't do to ios
cuz they don't allow u to download apks
or any app
man apple is some .... :/
Hi everyone, I was wondering if there was a way to change the anonymous sign in ID on a device, I'm trying to use Unity Lobby and would like to test some code on two editors using ParrelSync but when using AuthenticationService.Instance.SignInAnonymouslyAsync I receive the same playerID for both editors, because of that when I try to join a lobby it throws an error saying that I already am connected.
Is there a way around this? I've seen you can sign in with specific Google, Apple and Steam account access ID's but I'd rather not log in to my own personal accounts for a work project. Or can you just use fake ID's with these?
Is it smart to want something editable through the editor but static during runtime?
I was thinking a readonly ColorLibrary which has all the colors everything will use
also is even possible to having something serialized through the editor but static during runtime?
Yeah thats most things in unity, no?
Well I made it a singleton but it won't let me reference the 'non-static' colors
[SerializeField] private int real;
Isnt that the point of a singleton
Object.instace.color
Does anyone here know how to modify a UI TextMeshPro's RectTransform position at runtime?
oh I'm stupid I was just forgetting to type instance
Lol
no words
A second question wit hthis, if you cannot generate a different acount ID, can you manually overwrite it? The AuthenticationService.Instance seems to only have getters not setters, but is there a way around this that will allow you to overwrite the specific data
so. I have Vector2 value. up/down/left/right thingy
But it's local.
I also have a vector2 that indicates custom up.
So I need to somehow calculate absolute up/down/left/right values.
Any ideas?
transform.TransformDirection
Matrix4x4
could you elaborate?
actuall sorry that's more than you need
you just need a quaternion
someQuaternion * someVector rotates the vector by the rotation indicated by the quaternion
you just need to rotate the vector to whatever orientation makes sense
you'll need to elaborate on what "custom up" means
and "absolute up/down/left/right"
for example let's say you want to convert your x/y input to x/z
so, I have a Vector2, which would equal one of possible points on this red circle. I also have green vector. What I need: is to rotate circle to the point, it's up equals green vector
Quaternion rotation = Quaternion.FromToRotation(Vector3.up, greenVector);
basically, what I have is blue vector, what I need yellow
I mean yellow is literally just greenVector.normalized
not sure how blue is related
if you want the rotation from blue to yellow, that's what my quaternion thing above will give you
because blue is not really up
it can be any direction
^
hmm
Quaternion rotation = Quaternion.FromToRotation(blueVector, greenVector);
now with the blue instead of Vector3.up
And yellow is still greenVector.normalized
I'm a bit confused why I need quaternion here, since I need Vector
or you mean I then should obtain euler from it?
because I don't understand why you are bothering to mention the blue vector unless what you want is a rotation from blue to yellow
If you just want the yellow vector, it's greenVector.normalized
Maybe explaining your actual issue will help because this is probably oversimplified
Why would you want euler angles unless that's what you're looking for
Quaternion is already a rotation representation, and a much more useful one than euler angles
angle between them would equal angle between normal up and green vector
can you explain the actual thing you're trying to do
Then you want this:
Quaternion diff = Quaternion.FromToRotation(Vector3.up, greenVector);
Vector3 yellow = diff * blueVector;```
I have input from gamepad stick (blue vector), I need to make it so when stick looks up, character also looks up. But since camera angle does not match values from raw input, I need to adjust it to camera->character vector
basically, camera can look to south, while raw input gives me north. Thus character must look south, where camera looks
3d, where camera acts more like in a platformer
I haven't played it 😅
any 3d mario game
if stick goes south - I want to see face
Vector3 cameraForward = myCamera.transform.forward;
Vector3 projected = Vector3.ProjectOnPlane(cameraForward, Vector3.up).normalized;
inputVector = Quaternion.LookRotation(projected) * inputVector;```
can someone help please
I was getting confused by the whole "looking up" thing. @vague slate
have you followed what it says?
#📱┃mobile for better android build help
its for vr
this is an Android problem
oh ok
nothing to do with VR
^
yep, that was it, thank you,sir
could you explain though, what actually happens here math wise? I really want to learn why it's done the way it is
taking the camera forward, projecting it on the x/z (horizontal) plane to "flatten" it, then creating a rotation for that direction (the quaternion LookDirection)
Last part is just rotating your input by that rotation
question about the line with Instantiate(), why is the cast labelled as redundant?
I'm following a book, and it said that without the typecast, it will spawn a Object not a GameObject
Instantiate returns whatever type you passed in
oh, so if I multiply quaternion with vector that would equal to rotated vector
I see
you passed in GameObject so it returns GameObject
ah, so this is line is wrong?
yeah idk where you're reading that
actually I think it used to be that way
it's ooutdated
Hasn't been that way in like 6+ years
^^
oh yea that's true
also, projected vector here would be a vector between camera and point it looks at, but on x/z (2d space)?
That would be green Vector I was talking about I guess
I didn't like video tutorials, so I settled with books
I think I'll try hybrid, some tutorials and books
but thanks for the help
I think I'll stick with this book till the end, and try to make simple stuff on my own
I did make a game that followed a tutorial from start to finish, and did learn the basic layout of Unity
https://cdn.discordapp.com/attachments/897435373540618242/1077608267288690869/Weird_Unity_Bug.mp4 anyway to stop this ?
It only happens when the ball hits the corner of the player and my scripts are really simple movement and spawnner scripts
non-code advice, but you might wanna lower the bloom/glow effect
it's a bit distracting and hurts my eyes
ok cool thank you
but why does my issue happen
its very weird and it always happens
like everytime it hits the corner
void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
waveIndex++;
hasSpawned = true;
}
SwitchingSpawner(hasSpawned == true);
}
void SwitchingSpawner(bool spawned)
{
switch (waveIndex && spawned) <=== this line got error
{
case 1:
Instantiate(waveSpawner[0]);
hasSpawned = false;
break;
hi sorry. I'm trying something here haha but why is that line got error? it says && cant be applied to bool? but i thought that worked
What are you trying to do?
A switch statement will compare the input with all cases below it, for example wave Index looks like it is an integer, so case 1 works when wave Index on its own is an input.
With the && however you are saying the input for the switch is a boolean, and the boolean is made up of the conditions of (waveIndex and spawned), which means you trying to compare if waveIndex is a boolean value.
The error can be seen a bit better if you think of it as an if statement
if (waveIndex && spawned)
is equivelent to saying
if (number && true / false)
I don't believe C# lets you do Boolean logic directly on ints, as if (4) doesn't really mean anything.
If you are trying to do a conditional for if the object has spawned then what wave is it, then you just need to put the switch in a if statement
if (spawned)
{
switch (waveIndex)
{
....
}
}
hope this helps
ahh ok thanks!! i will copy this method 😄 i want my spawn method to spawn only once, thats all ahah
btw ty again for this method.
No trouble, hope it works ^-^
Im making a top down mini golf game, and it works fine normally, but when i add a circle collider 2D it pretty much just breaks and the ball moves on its own, any ideas on whats causing that or how to fix it? The radius of the collider is larger than the ball
If your object has a Rigidbody2D it will move according to gravity and physics
so why would it be working without the collider, what could cause the collider to move the ball on its own
is there any way i can connect a objet to a camera with script
define "working"?
you can use cinemachine
i ran i to a isue with my networking when i nea to synch cams in base the cam has to be off nad if its of its not showing the IK
wrong reply my bad
cinemachine
it only moves when i want it to, when i hold right click, drag the mouse, and let go, then the ball finally moves. but with the collider attached, it just moves randomly when i play the scene
also i did some debugging and its related to the rigidbody2d
I've got a question about which is more efficient. Right now I have a prefab panel that will be instantiated multiple times, and the prefab has 3 children (hpSlider, hpTextValue and nameText). In this case, I need to be able to reference the children objects to change their values periodically. Is it more efficient to spawn in the full prefab and use Transform.Find() to get the children, or is it better to break the prefab into pieces and instantiate the panel, and then instantiate each child separately with the panel as the parent? As a worst case, I'll be instantiating up to 16 of these panels at a time at most.
but i dont know what is the exact issue
but wothout the stupp being atachet to the camera recoil and way wount work
i tried
you should do neither.
Put a script on the root of the prefab and only interact with that script
that script can reference its own internals and do what it needs to do
i was thinking about conceting the wapons to the cammera after the syncing of the cameras
so the ik will be shown in the prefab
Could you elaborate a bit further on that? Would the script pull in the children to change their values?
move it a bit to give a placebo effect
the prefab script would have direct references to the internal UI elements it needs to change
nah i nead a way that the camera stays disbale in orefab but the child in prefab unther the cam will be sean
Ok, so on the script I would make public Slider and public Text variables and just drag in those parts of the prefab into the script on the parent prefab object?
i want to hand so be still the in the prefab even tho the camera is off so i can sync the cams and let other ppl see the IK
and it has to be under the cam otherwise the recoil,sway doesnt work
hey guys, im working on a game and am adding throwable grenades. I made this script but unity keeps giving me errors and dont know why, can anyone tell me what i am doing wrong? heres the script:
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grenade : MonoBehaviour {
public float delay = 3f;
float countdown;
bool hasExploded = false;
// Start is called before the first frame update
void Start() {
countdown = delay;
}
// Update is called once per frame
void Update() {
countdown -= Time.deltaTime;
if (countdown <= 0f && !hasExploded)
{
Explode();
hasExploded = true;
}
}
void Explode ()
{
Debug.Log("imabatakam");
}
}
`
Show the errors
configure IDE also
what
shar evideos as mp4 so discord can encode it please
@lone relic click on the erros and VS will show the line which is problematic
I can't download things on this laptop
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
bruh why did video send like that
im installing vs rn
what are we looking at ? the rigidbody ?
not code related esp #archived-code-general
where should i do this then, im new to the unity disc
it was the circle collider, it just broke after i added it, the video shows it working just fine beforehand
Hi there
does anyone know how to use FindSelectable properly in UI?
I'm trying to manage navigation of a GridLayoutGroup manually but the function doesnt returns only null...
_buttons = GetComponentsInChildren<Button> ().ToList ();
foreach ( Button button in _buttons ) {
Quaternion rotation = button.transform.rotation;
Navigation nav = new () {
mode = Navigation.Mode.Explicit,
wrapAround = true,
selectOnDown = button.FindSelectable ( rotation * Vector3.down ),
selectOnUp = button.FindSelectable ( rotation * Vector3.up ),
selectOnRight = button.FindSelectable ( rotation * Vector3.right ),
selectOnLeft = button.FindSelectable ( rotation * Vector3.left ),
};
button.navigation = nav;
}
Heyy, working on DAY / NIGHT cycle
Im trying to lerp the color of camera's background color
Problem: the background changes instantly, instead of lerping, no matter the time i set
Camera cam;
public Color dayColor;
public Color nightColor;
// START
void Start()
{
cam = GetComponent<Camera>();
}
// UPDATE
void Update()
{
cam.backgroundColor = Color.Lerp(dayColor, nightColor, 10);
}```
isnt lerp supposed to be between 0 and 1
also
Lerp with 10 always just gives you the second parameter back
you need a value that updates
Color.Lerp(dayColor, nightColor, 10); is completely equivalent to just writing nightColor
it will always update instantly if you dont have a changing value
so t is basically where the interpolation lies, not the time it takes?
yes... it's not magic
it's just a math function
it doesn't spawn a coroutine or something
it just returns a value
Oh, ok, thx, but is there a way to controll the time it takes?
float t = 0;
float duration = 10;
void Update() {
t += Time.deltaTime;
t %= duration;
cam.backgroundColor = Color.Lerp(dayColor, nightColor, t / duration);
}``` something lioke this @upbeat dust
float time = 0;
void Update()
time += Time.deltaTime
Lerp(day, night, time / number_of_seconds)
exactly
mine is very pseudocode
oh, so basically you increase the t hence slowly advancing the interpolation?
oh yeah %= is a good idea
that is how time works yep
Perfect, tysm guys)
I recommend using a Gradient btw instead of two colors
and have the start and end colors be the same
so it loops smoothly
thx for suggestion, ill research on it)
but originally i was thinking of inverse lerp
Hi everyone, I am looking to store a value during the pre build step using the code below, this seems to work and I get a debug log in console telling me the correct Android.bundleVersionCode, however when trying to access this value again later through the player preferences, PlayerPrefs.HasString returns false for "Version". I'm thinking player preferences may not work during the pre-build phase, is there another way I can acomplish this?
#if UNITY_EDITOR
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
public class BuildVersion : IPreprocessBuildWithReport
{
public int callbackOrder => 0;
public void OnPreprocessBuild(BuildReport report)
{
int version = UnityEditor.PlayerSettings.Android.bundleVersionCode;
PlayerPrefs.SetString("Version", $"{version}");
Debug.Log($" <color=#00AA99>§»</color> Build Version: {version}");
}
}
#endif
Why can't you just use UnityEditor.PlayerSettings.Android.bundleVersionCode later on?
Its editor only, so doesn't work in the build
well PlayerPrefs isn't going to set anything for the build either
PlayerPrefs is a local thing for your computer
it's not part of the build
Ah good point.. I forgot about that xD
it also is different in editor and in a build anyway
you'd have to write the data to a serialized asset
A ScriptableObject for example
or a file in StreamingAssets
Right, I'll look into that then. I've used SO's before so shouldn't be to hard to get that done. Thank you
Sorry, I was being a bit dumb xD
is there a way to merge materials in play time?
like i have the path of material. i change the material at runtime then when i stop playing i want to get that material and merge the actual asset
you can do smth like this with prefabs. prefabutility.mergeprefabinstance smth like this works fine
but i couldnt make it for material
is there a way to do it?
if you modify the asset itself it will change permanently
just make sure you're using .sharedMaterial instead of .material at runtime
.material makes a copy
thats not what i want actually
i want to keep .material
i want to get that instance material and find the actual material in assets (i have path of it) then merge it
something like this but this doesnt work
idk if im stupid but (its saying that playerCamera is unaccessble becous of security)
Dont cross post please
If goMaterials is an array of direct material references you can just modify them directly
there's no need to deal with AssetDatabase etc
and no need to make a new material
i thought editor extensions is right channel for this sorry about that
gomaterials is actually an array of gameobjects all materials
paths is path of the actual materials path
"gameobjects all materials"?
in assets folder
what does that mean
think of a simple cube get that renderer and its materials
according to your code it's just an array of materials directly
no cubes
no GameObjects
etc
and that's just fine
you can modify them directly
i.e. stop doing the new Material thing
i cant modify them because they are instance material when i stop playing changes dont save thats what im trying here
saving instance material
they are only instance materials if you created them at runtime
just... stop doing that
i know this but this is not what i want actually because if i do this way i will lose references
imagine of a prefab, if i do this i have to reference it in inspector
if you want to modify the existing material - modify the existing material (references won't be lost)
if you want to create a new material, do that
what i want like literally merge material
just modify the existing one
- get a reference to it
- modify it