#archived-code-general
1 messages · Page 318 of 1
Are the methods being called the number of times you expect?
It looks like they're being called once as the objects become non-tracked, then again when they become tracked.
Moving the = true into Start would matter if the Default Observer Event Handler component was calling your methods before Start ran
which is possible
If they are only being called twice, and the second call sets both variables to true, then it should work fine
Make sure you don't have multiple Object Rotation Manager components in your scene. That could produce confusing logs.
Does anyone know why rider generates seemingly weird markdown files?
I have one component set to the imageTarget of Cube and another to the Cylinder one. So two instances of the script. Is that an issue?
so you have two Object Rotation Managers?
One single script, but dragged to both of these
So both ImageTargets have that script
Those are two completely unrelated components.
They don't know about each other.
Sounds like you want to have one object rotation manager.
Probably. How do I create a single instace for both of them?
by only having one component
You mean, only setting one instance to one ImageTarget? And for the other imageTarget, try to access the instance of this one?
No. Both of these "Default Observer Event Handler" components should be targeting the same "Object Rotation Manager" component.
One should be calling the SetCylinderInView method and the other should be setting SetCubeInView
i also noticed that this is calling the wrong method
it calls the Cube method in one place and the Cylinder method in the other
Oops, missclicked. Changing many things in a short time
But you are calling the class that way
So no functions can be called
You have dragged in the script asset itself. Don't do that.
drag in the Object Rotation Manager component that's in your scene
I am a little bit confused. Where do you mean by scene?
The hierarchy displays all objects that are in the scene.
Where is your single Object Rotation Manager?
I am guessing it has to appear in the hierarchy, isn't it
So I don't have it as of right now
And only have the script in asssets
It needs to be attached to an object in the hierarchy.
You already have one attached to an object. You sent a screenshot of it earlier.
Oh, I get it now. So now that I have attached a single Object Rotation Manager, to the Cube ImageState for example, I can call its functions
But, how do I access to this one from the other ImageTarget (Cylinder one)
I hope I'm understanding it correctly
just drag in the object with the "Object Rotation Manager" component on it
it can be from a different game object
I apology for my slowness, I am trying to do that but I can't seem to select the component and drag it onto the other one, since I have to click on the other ImageTarget to open its inspector.
I have tried opening two tabs but they reference the same
you dont need to select the component, you can drag the game object that has the component on it and Unity will sort it out
Drag the game object.
public class BackgroundGen : MonoBehaviour
{
// distance for level to spawn from the player
private const float PlayerDist = 15f;
// object references
[SerializeField] private Transform Background1;
[SerializeField] private Transform BackgroundStart;
[SerializeField] private PlayerLogic player;
// the last end position of the most recent background to spawn
private Vector3 lastEndposition;
// gets player pos
public Vector3 GetPosition() { return transform.position; }
private void Awake()
{
lastEndposition = BackgroundStart.Find("EndUp").position;
}
private void Update()
{
if (Vector3.Distance(player.GetPosition(), lastEndposition) < PlayerDist)
{
// spawn BG part
SpawnBGPart();
}
}
private void SpawnBGPart()
{
Transform lastBGPartTF = SpawnBackgroundPart(lastEndposition);
lastEndposition = lastBGPartTF.Find("End").position;
}
private Transform SpawnBackgroundPart(Vector3 spawnPosition)
{
Transform BackgroundTF = Instantiate(Background1, spawnPosition, Quaternion.identity);
return BackgroundTF;
}
i got this code from an endless level tutorial as i thought it would work with backgrounds also. my goal is to have backgrounds spawn in all directions. when the player gets a set dist from the last endpoint. but i need it in all directions. how would i go about this. my idea is just to impliement the multiple end points? and ajust the code depending on which direction the player is travelling? but does anyone have any suggestions?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I have a problem with the assets bundle, When i want to create one I got this message:
Moving Temp/unitystream.unity3d to D:/<MyPath>/Assets/AssetBundles/base: Acces refused.
Why is that? I can't find anything online except this post:
https://issuetracker.unity3d.com/issues/building-an-asset-bundle-varient-results-in-an-error-when-there-are-identical-files-at-different-directory-levels
How to reproduce: 1. Open the attached project '1197194repro.zip' 2. Execute 'Assets -> Build AssetBundles' Expected results: Ass...
Perhaps your application doesn't have access to that path
It's the unity application. The path it litteraly the project folder, if the unity app does not have access to it's own folder, what's going on
the unity app is not installed in your project folder
you may have put the project folder somewhere it doesn't have full access to
Hey, can inherited functions use extra parameters or can they only use the parameter the base script has ?
You cannot change the signature of an overridden method
the signature has to match exactly
it wouldn't make any sense otherwise
how would you possibly call it?
By the new inherited script .-. but yeah its alright
But there's no point in inheritance then
inheritance is so other things can call a polymorphic function on a reference of the parent type
I Think i already know how do use it the way I want, so its alright, thanks for the answer and btw just answer the question instead of saying ''what you're saying does not make sense''
I don't know why you are quoting, no one said that
I moved the entire project folder to the documents folder and still the same issue
Are you using OneDrive or somthing similar?
For the project or in general?
in general
I don't use it but i think it's enabled
then move your project to a path that OneDrive does not backup
Now it's in Documents, and onedrive does not seem to access it. And before it was in another drive and onedrive does not have access to it
Documents is backed up by OneDrive
It's still happening in another drive tho
external USB?
so something like D:\Unity
Yea
but not on an external drive
On another internal drive
ok, make sure your path has no special characters, only A-Z and 0-9
Unity can be real finiky about that
I'll try to move
Nope this time the path is D:/Work/Project/ and it's still say access refused
Have you tried building the bundle to a path outside the project path
I found the issue.
I'm building an asset bundle for a DLC, and i named the DLC folder "Base" for the default content. And my asset bundle name was "base", I think it was trying to overrite the folder or something like that.
Sounds about right
D:/<MyPath>/Assets/AssetBundles/Base/base
Well the bundle was created in AssetBundles path, so at the same level as Base folder
Now that this is solved, do you know if it's the right path to go for DLC?
sorry, no idea
No problem, thank you!
guys, there is this dotnet folder in my C drive, program files. i was wondering can i just delete this one? it is of 7 gigs and i need some space in C, is this unity related at all? i downloaded android studio quite some time ago could it be because of that? i downloaded it to get the jdk sdk stuff for unity.
dotnet is related to unity yes
but this seems to be runtime ? or is it sdk
I'm on mac so i forgot where windows saves it, ig Program Files makes sense
I dont recall that being 7gb tho
7gb dotnet folder??
mine is only 740mb
but yes, it's important
but I do not understand as to how many things you got for dotnet that it's that large
the size probably depends on what workloads and versions of dotnet they have installed. for example, mine is nearly 4gb
first check how many you have installed
dotnet --info (in terminal)
so @hidden compass is there a reason you use where T : Singleton<T> ? my monobehaviour one uses where T : MonoBehaviour
Also what's the benefit of making the class abstract again?
Using where T : MonoBehaviour allows any MonoBehaviour-based subclass to use the generic class, but it doesn't enforce the Singleton pattern. Without additional checks or logic, multiple instances of the subclass can be created, which goes against the Singleton pattern's intent of having only one instance.
Making the class abstract prevents it from being instantiated directly. This ensures that developers can't create an instance of the abstract class itself, but instead must inherit from it to create singleton instances. This helps enforce the intended usage of the class as a base for creating singleton instances.
I feel really dumb, but is there any common reason why the Transform point of child objects don't match the parent transform, even when their local positions are set to (0, 0, 0)?
In my inspector the childs are all zero local, but they're considerable off from the parent transform. I'm perplexed.
An artist I'm working with prob exported these from Blender, if that makes a difference
nothing really wrong with the way ur doing it.. but my version just stresses the Singleton pattern a little better
was my source.. and then i got some help from the beginner channel to help me refine it a bit
yeah I just want to make sure what I'm doing is actually correct to the pattern (at least mostly)
if the stuff you said didn't feel like it slightly defeated the point of a singleton I wouldn't fix it 
Almost definitely the parent or child origin is not where it should be in the model
Sorry, what is 'origin' referring to in that case? Is that something from the 3d model import pipeline?
its the origin of the mesh
yes, it is the 'center' point of the model
(origin/pivot, meaning the specific place in the model that would be at 0,0,0)
yes
ohh, so when they set it up in Blender, they did the work "away" from the center origin point?
Ok so whenever I try download the xr plugin management it’s always says there s an error so if someone could dm me thanks.
yes, they probably 'forgot' to apply the transforms when they exported
thanks for this info. saved me some trouble
May you help what?
yeap, for 3D models, its in the modelling software where the pivot/origin is placed
Hey guys, I have this weird issue happening.
I was trying to change some of the quality settings of my mobile build of my game. Originally I changed the quality using Edit > Project Settings > Quality and then I changed the current quality to PC (from mobile)
However as soon as I did this I started having build problems on my physics device. In editor the game works fine, when I build for mobile (iOS) I just get a (somewhat) empty screen completely missing all my assets!
Things I Checked already:
- Added all scenes to build
- Rebuild the XCode project
- Close unity and re-open and then rebuild
- Changing quality back to mobile
I Really can't get this to build on my phone anymore when I litterally had it working a few hours ago losing my mind over this.
this is a code channel
interestingly it flashes pink when I try to load the game, and it shows my line renderer
well it is also the code-general channel
yes code-general. because this is a code channel
id:browse to find a channel relevant to your question
- not really helpful, but whatever
- you can see plenty of people above talking about code-general side of things
please learn to read
compiling and building the project can be seen as "related to general coding concepts in unity"
okay then show the code you are having trouble with
yeah dude if ur not gonna help, at least dont be toxic lmao
my guy, you were the one arguing about where this question belongs. you should post it in the most relevant channel so you actually get help instead of posting in the wrong channel then bitching that it isn't actually the wrong channel because you didn't bother reading the full name of the channel or its description
general , as in .. non-beginner code
- Didn't post in the wrong channel I shall remain adamant about that
- if anything you've completely derailed the conversation here by being extra pedantic about the topic of the channel (which I assure you was on topic)
- I actually just looked through every other channel and I can't find one thats more suited for the topic at hand.
well if you didn't post in the wrong channel, then share the code you are having trouble with
Okay. I believe you that it's on topic.
Now show the !code you need help with
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this ^?
that doesn't show any code
its almost like, u can have coding related issues
without the issue being in the code
Technically speaking: Unity C# Compiler Toolchain .NET
lots of arguing that its relevant to the coding channel, but you called boxfriend toxic when he asked to see code.
There is both #💻┃unity-talk and #📱┃mobile
yeah because they obviously had toxic intentions when they asked such a question
oyu can see plenty of people posting in this channel without having SPECIFIC code they are looking at
so instead of arguing and wasting your own time, why not just post it in the correct channel? This is a waste of everyones time
Well if literally anything made in code can be asked here I was wondering if anyone had any tips for beating Hecate in Hades II? I feel like I just literally don't have enough damage, like everything I do is barely making a dent. Do I just need more Arcana?
actually i'd hoped you'd realize you were being ridiculous in insisting that it was a code issue because it wasn't related to code at all
Its quite litterally a toolchain issue
what is a toolchain issue?
not to mention the dude before me was asking about transforms and origins, I don't see how THATS a coding issue
original issue
still confused on how changing quality settings would be affecting code at all
this seems related to asset database
I would first try to reimport all Library
I was messing with the RP Assets, honestly I'm not sure why it wont render my scene anymore
where is this located?
To be clear about this: neither of them are, and occasionally non-code questions get answered here mostly because people don't check what channel they are replying in.
Your post is not suited to this channel.
I'm trying to access the Music folder on my android device to see what files are in there but I can't seem to get it. Anyone know how?
Don't think unity has built in way to access MediaStore directly
unity does let you call external plugins / code though, i bet you can access native kotlin code like that
So I'd be relying on reflections?
I suppose, how expensive can it be anyway? You'd only be getting some paths
So I have a simple input buffering script for processing weapon inputs and handling multi-button chords. It's giving me a NullReferenceException and I don't understand why.
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class CombatInputBuffer : MonoBehaviour
{
[SerializeField][Range(0, 1)] private double _chordingTimeout = 0.01;
[SerializeField][Range(0, 1)] private double _bufferTimeout = 0.1;
private double _chordingTimer = 0;
private double _bufferTimer = 0;
private List<InputAction> _bufferedInput;
public IReadOnlyList<InputAction> BufferedInput => _bufferedInput;
private bool _isChording = false;
void FixedUpdate()
{
_chordingTimer -= Time.deltaTime;
_bufferTimer -= Time.deltaTime;
if (_isChording && _chordingTimer <= 0)
{
CommitChord();
}
if (_bufferedInput != null && _bufferTimer <= 0)
{
_bufferedInput = null;
}
}
private void CommitChord()
{
_isChording = false;
_bufferTimer = _bufferTimeout;
Debug.Log("Inputs: "
+ (from action in _bufferedInput select action.name)
.Aggregate((a, b) => a + ", " + b));
}
public void OnInputReceived(InputAction.CallbackContext context)
{
if (context.performed)
{
if (!_isChording)
{
_bufferedInput = new List<InputAction>();
_chordingTimer = _chordingTimeout;
_isChording = true;
}
if (!_bufferedInput.Contains(context.action))
{
_bufferedInput.Add(context.action);
}
}
else if (_isChording
&& context.canceled
&& _bufferedInput.Contains(context.action))
{
CommitChord();
}
}
}
NullReferenceException is on _bufferedInput
Yet, as far as I can tell, the following intended invariants do seem to be true everywhere which should prevent that:
_bufferedInputis only ever accessed by the code when_isChordingis true.- When
_isChordingis set to true,_bufferedInputis initialized to an empty list. _bufferedInputis cleared to null on a timer which is longer than the one which sets_isChordingto false
Did you write this code yourself? Throw a debug in that if (!_isChording) and see if its ever even running. Thats the only area where I see you assign something so it wouldnt be null
Yeah, I wrote it myself. I can check, but that's the only place where the _isChording flag is set to true, so how would I be getting the NullReferenceException in the first place if that wasn't running?
well first thing is you should specify what line the error is actually happening on, the stack trace of it in unity should also tell you when its being called as well. Though really its probably just that _isChording isnt what you think it is at a certain point.
It's happening in like three different places, I'm focused on the invariant violation though, since if the invariants weren't being violated, the error couldn't happen
It's happening on the Debug.Log line (actually an ArgumentNullException, but same thing), and at the contains checks in OnInputReceived
FixedUpdate is not Update, I haven't trawled your code in detail but are you sure things are being called in the order you expect?
Why not attach the debugger and see...
honestly why even bother creating new instances of the list? just clear the list when you need it to be empty and reuse the same instance
True that, but the logic error would still exist if there is an expectation of a certain call order.
i have trouble following this code, but it looks like theres just some random and independent logic happening between the chords and the buffered input. the bufferedInput can just be independently set to null from fixedupdate without care about anything else. then nothings really stopping an NRE from happening like anywhere else
you could also do what boxfriend said, but i suspect theres more issues than just null here. Like it'll probably not be using the correct values if theres already this issue
So, that may not be clear, but _bufferedInput can only be set to null in FixedUpdate when the _bufferTimer expires, which is longer than the _chordingTimer which resets _isChording
... At least, that should be the case, but I added an assertion to that and it's not.
well its clear that theres an error, where it is null when it shouldnt be. what you wrote is what you assume is happening, the debugger or just simple logs should point you in the right direction
I mean its a fun thought activity to solve the logic error by thinking but if you actually want to fix your problem attach the debugger set the break points and see what is actually happening.
I'm stupid
I forgot to initialize the buffer timer
Or rather, I for some reason initialized it at the end of a chord, not the start
Yeah, I wasn't trying to solve it just by thinking, I was peppering in assertions while we were talking 😅
Ok, I'm confused now. Everything here should be happening in one thread, right? No concurrency?
(NullReferenceException is fixed, but I'm running into a different issue now)
yes, unless you specifically do any multithreading yourself there will not be any multithreading happening on your monobehaviours. and unity messages like FixedUpdate will never be multithreaded
private void CommitChord()
{
Debug.Assert(_bufferedInput != null || !_isChording);
Debug.Assert(_isChording);
_isChording = false;
Debug.Log("Inputs: "
+ (from action in _bufferedInput select action.name)
.Aggregate((a, b) => a + ", " + b));
}
How is this getting called twice without that Assertion failing???
if only someone mentioned using a debugger ...
Ah, correction, the question is "how is the performed event happening twice for a single button press?"
Step with the debugger and you'll figure it out
A tool that lets you see exactly what gets called when... and the (stack) history of what called it ...
🙂
If you subscribed to it twice for example
I didn't
Are you sure they are all pointing to the right object?
Yeah, but moreover, it's only getting called twice for "Performed"
Not for "Canceled"
So step through the darn thing...
I don't see performed or canceled in that screenshot
That's not stepping through with a debugger.
I'd need to step through the entire input loop wouldn't I?
There's no way we can help you without any context and code.
you are also calling that functions from other areas like fixed update. this whole thing seems like spaghetti
You can use conditional breakpoints.
Put a break point on the thing that is getting called twice, look at the call stack.
Lots of options here.
Learning how to use the debugger properly is way more important to your success than solving this one logic error, seems like a good time to do so ... two birds with one stone and all that.
(and yes I know some people go their entire career without using debuggers, but it is the best tool for many jobs, this seems like one of them)
I know how to use a debugger. I was lazy to do so as I don't expect to get relevant information from it here. I know that I'm getting two calls to OnInputReceived for a "performed" event and only one for "canceled," which doesn't line up with my understanding of how the input system works
you do? 😛
If you have the call stack of whats calling the code you don't expect to be called, its very very likely its going to tell you more than you know now.
hell, even the stack trace alone from the debug.log should tell you
I mean, yes, but it's going to give me details of Unity internals which I have no clue about, no?
But set break points on the thing called twice and the place that the flag changes.
Stack trace is identical for both, running off into Unity native immediately
Processing: Weapon 1, Performed
UnityEngine.Debug:Log (object)
CombatInputBuffer:OnInputReceived (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/CombatInputBuffer.cs:52)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr) (at /Users/bokken/build/output/unity/unity/Modules/Input/Private/Input.cs:120)
You can see which bit is happening out of the order you expect, or you can see if you 've got something being called twice you don't expect to be, the point being it will probably tell you something about what is happening.
Like, the key thing I don't understand is, how can I get two performed triggers but only one canceled?
I thought the two have to occur in pairs?
I mean, one is button down, the other is button up?
You can make an educated guess based on the function names.
did you subscribe the event in code ever?
... It's because I set the button to "PressAndRelease" thinking that that was necessary to send both button down and up
like some ctx.performed += ...
Event that is triggered when the action has been started but then canceled before being fully performed.
No, I'm using the Unity editor wiring
The Player Input stuff
So it is certainly possible to have more performs than cancels.
That said, I think I solved it
This here
start leads to perform or cancel
TBH, I'm having trouble wrapping my head around the new input system in general. I'm half tempted to just use the old functions for listening to the hardware more directly
But I figure it's important to get this stuff down
If using the new system you should probably write your own interaction to handle buffering.
How do you mean?
Implement IInputInteraction to make your buffering part of the system rather than something that sits outside of the system.
I'm guessing at the context of your game, but it seems like what you would want to do is send Performed at the right time.
So your buffer is effectively a custom interactions that knows when a button is down (probably sending Start on press), and if it falls in the allowable buffer/window it sends Performed at the right time (or Cancel if the buffer expires).
So, for starters, I'm trying to set it up so chords can be processed, e.g. pressing A + B at the same time
Also input buffering for chaining attacks, so if you press a button before the cancel window of the attack begins, that input is still around, but that I don't think I can implement within the new input system
I would love it if there's some way to implement the chording within it
Hmm maybe not ideal then, a fighter probably has too much nuance in the control.
At some level of complexity you would be fighting the system rather than gaining from it.
Yeah, that's what I figured. I'm going to implement the flow as an FSM, I just need to be able to take arbitrary combinations of the three attack inputs
Not actually a fighting game lol, but yeah fighting game style controls. It's a Monster Hunter clone
Our designers want to take our battles along that Monster Hunter route, I prefer the current system (which is kind of a simple combat which then leads you to an Auto Battler). Reflexes not my thing.
Anyway off topic!
FSM is going to be fun to implement haha. I'm still debating between defining the structure in code or implementing a Graph Tools UI
Not sure if XNode is still maintained but it was a nice API for very quickly and easily creating custom tree like structure in editor.
Unfortunately looks like no. There is this from Unity themselves: https://github.com/needle-mirror/com.unity.graphtools.foundation/blob/master/README.md
But it also hasn't been updated in 3 years and is still in preview
https://forum.unity.com/threads/graph-tool-foundation.1057667/page-4#post-9647582 Most recent update I can find
这是一个简单的案例:):
iLoveNiu/GTF-Test (github.com)
It seems as of 2023.1.0b16, the API has changed and this project no longer works out of the box -...
I wouldn't consider this a newbie question. I suppose, this may be achievable by first selecting the InputField's Selectable, then activating the InputField itself. I'm not sure and you gotta check it out.
inputField.Select();
inputField.ActivateInputField();
I see, thx mate.
anyone know why there is a big delay with my inputs when pressing two different keys? Say I try to press the key 2 and key 3 ability together, only one will trigger. https://gdl.space/opuwitesor.cs
I'm making a 3D isometric style game, made pretty much the basic character controller however since the game is isometric, my camera is rotated 45 degrees on the Y, so the player is always moving 45 degrees to the left (45 degrees north west of the camera you could say) how do i make it that when i press W the player moves directly forward of the camera? Code: https://gist.github.com/Winter-r/c023d12a56575925d9a6f3270f92c49a
Don't you assign a cooldown yourself here?
if (ability.CanActivateAbility())
{
StartCoroutine(ability.TryActivate());
OnAbilityUsed?.Raise(new AbilityUse(skillIndex, ability.GetCooldown()));
}
Also, this doesn't make sense. The Action cannot be unsubscribed like like.
abilityAction.action.performed -= ctx =>
TryUseSkill(Array.IndexOf(
abilityAction.action.controls.ToArray(), ctx.control));
So have a method which does what you do when subscribing and unsubscribing it
And this is a List, right?
abilityAction.action.controls
You may use the List.IndexOf(this) method instead of the Array.IndexOf
So you want the player to move in the direction of the camera?
Do it also include rotating the player?
Hey guys, I have a script with one function like so:
public IEnumerator Shoot() {
//If trajectory is even possible, then create the projectile object and apply said trajectory.
if(GetTrajectory(out Vector2 velocity)) {
GameObject pj = Instantiate(projectile, transform.position, new Quaternion(0.0f, 0.0f, 0.0f, 0.0f));
pj.GetComponent<FlyingEnemyBulletBehavior>().parent_flying_enemy_ref = this.gameObject;
pj.GetComponent<Rigidbody2D>().AddForce(velocity, ForceMode2D.Impulse);
}
yield return new WaitForSeconds(launch_rate_seconds);
has_shot = false;
}```
Im trying to set a public variable "parent_flying_enemy_ref" inside a script called "FlyingEnemyBulletBehavior", that belongs to the instantiated GameObject variable "pj", via the current script that this function resides in^
for some reason the line
pj.GetComponent<FlyingEnemyBulletBehavior>().parent_flying_enemy_ref = this.gameObject;
causes the rest of the function to not function
does anyone know why? if I need to provide more code let me know
removing that one line I talked about makes the function work again
In what way does it not work exactly?
basically the function spawns a projectile gameobject, which is just a ball, and launches it with a specific velocity
normally this function does exactly that, but with the addition of the line I spoke of, it doesnt create projectile gameobjects and launch them anymore, nothing happens
Add logs after the line to confirm that the code runs, and make sure errors aren't disabled in the console
it doesnt, I tried the logs approach
nothing printed
nothing before as well
which is quite confusing
And the logs print if you remove the line?
yes, and the function works as expected
Show the FlyingEnemyBulletBehavior script. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
one sec
the cool down is handled separately, I was talking about the actual key presses from the input system. I had the action map set as button instead of value which was causing the issue. However when I press both keys at the exact same time, only one is registered still. is that a limitation with the input system or am I doing something wrong. I have my action map Skills with binds for 1, 2, 3 etc. Also, I assumed that's how you subscribe for the triggered event, am I mistaken? it works perfectly fine
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyingEnemyBulletBehavior : MonoBehaviour
{
public GameObject parent_flying_enemy_ref = null;
private Rigidbody rb = null;
private Collider2D col = null;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
col = GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
}
}
@mellow sigil
why are you mixing 2D and 3D components?
ah my mistake
forgot to add the 2D for the rigidbody
but that wouldnt be the issue would it?
Can you show a screenshot of the full console? There should be at least a warning about the invalid quaternion
one sec
🗿
i didnt even attach the script
that im trying to call
thats why it wasnt working @mellow sigil
- So the message you have isn't printed multiple times? You have mentioned you have bindings. As far as I know, the bindings, which have the keys supposed to be pressed together, should be composite.
- That's not how you usually subscribe to the event. This subscribes to the event, yes, but using this kind of subscription makes you unable to unsubscribe from this event.
So did you have errors hidden or why didn't you see the NRE error?
there was an NRE error, I missed it as I looked though the logs
😔
silly old me
thank you for helping though
hey there I'm wondering if anyone can help me think a solution for dragging a rigidbody from a pivot point instead of its center, my method works but positions are kinda odd when the object rotates, I need a second brain im almost suffering
Here's some relevant code
// This line is inside a method
_grabbingBody.AddForceAtPosition(
GrabDirectionTowardsCursor() * grabForceMultiplier,
GrabPointTransformed()
);
// ===================== FUNCTIONS & HELPERS ============================
public Vector2 GrabPointTransformed()
{
return _grabbingBody.transform.position + _grabbingBody.transform.TransformDirection(_objectGrabPointPivot);
}
public Vector2 GrabDirectionTowardsCursor()
{
return (PlayerCursorAttachment.CursorPosition() - GrabPointTransformed());
}
// This is what I do when left click is pressed, CursorPosition() is the position of the yellow eye sprite (which is another GameObject that acts as a cursor)
_objectGrabPointPivot = PlayerCursorAttachment.CursorPosition() - _grabbingBody.position;
_initialGrabPoint = PlayerCursorAttachment.CursorPosition();
Maybe use transform point then make a direction using world coordinates?
Actually, I don't think you need local coordinates. Just a position here with world coordinates
I'm actually confused about how AddForceAtPosition handles the given position
I'll read the docs maybe I missed something
I assume the problem is the arm is going further from the point you clicked, right?
So the question is, does the location you click give the correct coordinates or is it another issue because I'm not too sure of the requirements here.
yes, it changes depending on the rotation, like if it rotates 90 degress it still tries to grab the bottom part but from its own coordinates or something like that, I mean it makes sense if I used TransformDirection but can't think of anything else, 'cause most attempts made the body rotate like crazy lol
the coordinates of the click are accurate because I'm using a gameobject as a "fake" cursor, so it has the position properties
TransformDirection and TransformPoint deals with local position such that the object is a child to another, and you want to convert the local position relative to the parent as world coordinates
the hand is only visual, it moves to where the resulting position is, pretty much the offset between the box and the click
But, if used on an object not a child, I don't believe it does anything besides returning world coordinates
Ah, actually maybe im confusing myself. You would just grab the local coordinates via transform.local otherwise, so the method is useful to get relative coordinates without having them actually be child/parent.
void Start()
{
// Instantiate an object to the right of the current object
thePosition = transform.TransformPoint(Vector3.right * 2);
Instantiate(someObject, thePosition, someObject.transform.rotation);
}
Right, so say you want to always get a unit that's always on the right side of the object, you could use this method.
and you have InverseTransformPoint where you can get the exact local* coordinates of that position in space that's relative to another transform without having to child it.
TransformPoint is the equivalent to what I was doing before?
_grabbingBody.transform.position + _grabbingBody.transform.TransformDirection(_objectGrabPointPivot)
what space is _objectGrabPointPivot in?
wdym by space?
wait, you're using TransformDirection here with a position vector
yeah, that position is the pivot from where I want to drag, I'm making small changes to see what improves its behaviour
is playercursorattachment using ScreenToWorld?
No
What's the returned value of it then?
the objects position lol
public static Vector2 CursorPosition()
{
return Instance.cursorTarget.position;
}
Im not using positions provided by the mouse
so the cursor pretty much lives in the game's world
I'm trying to figure out why you don't just use world positions for everything. Wherever this cursor is, just grab the transform.position, and if you need a direction from the target (cursor position) minus the player position
I need to somehow keep _objectGrabPivotPoint attached to the objects rotation AFTER it has been grabbed, but otherwise use the cursor position no matter the rotation, I am not sure why am I failing on that last step
Oh, but the hand sticks to the point of the object, so there is some locality with the object going on i guess.
My math is most likely wrong but unsure where
It makes sence of what you're trying to do because you are holding onto that item without childing the hand to the object, so yeah these methods would be helpful.
So the problem here is where you click, you want to cache a local point onto that object you are holding.
the red line represents the correct place where I want to drag from, so perhaps I'm doing wrong modifications to _objectGrabPointPivot after it has been set with the correct values
https://docs.unity3d.com/ScriptReference/Transform.InverseTransformPoint.html
It may be this method you're looking for
world position to local relative to the box's position
tried using it and made everything fly, I'll read what it does exactly
how would you use it?
boxTransform.InverseTransformPosition(cursorWorldPosition)
this would give you the local point on the box from where you click
bugs are fun
Well, when you get the local point, and you want the hand to go to that point in world coordinates, then you would use :
Transform.TransformPoint
https://docs.unity3d.com/ScriptReference/Transform.TransformPoint.html
oops i used the wrong method my bad
so basically, cache the point when you click, and every frame afterwards if you want the hand to go to that position (or using some force method). You would use boxTransform.TransformPoint(cacheLocalPosition) to get a world point
so now you can devise a direction such that:
boxPointWorldPosition - handWorldPosition = direction
transformpoint behaves exactly as my previous method so, good thing I learned about this one at least yet the issue regarding the box rotation is still present, I'll turn it into a sprite with visible directions maybe it helps a little more
@fervent furnace thanks for your wonderful explanation, I saw that you've been typing for so long!😇
transform.TransformDirection is useful too, but what I can make out of your code is you're using a point for the parameters when it expects a direction
or maybe I am misunderstanding what that variable may be
I'm struggling to design how I want to handle data exactly in my project. I'm trying to design a simple RPG skillset, and this is what I've come up with so far:
A MasterAttribute script, which I then generate gameobjects off, for the actual skills, they look like the attached pic.
A manager script to create a defined sized array, then populate it
What I'm confused about is; In my own design I don't know how you would interact with the gameobjects (the attributes), but also with a player + enemies, how would I manage their attributes as well, seperately?
I am trying to plan a modular system that could be used for various data like currencies, stats, etc that can be extended in the specific items if needed.
Image
Just looking for advice, this seems like a bad approach, but everything else I've seen is too simple, or hard coded...
I would debug to make sure that the point you're getting with InversePoint is correct. Ideally, click the top left corner of the box each time and flip it, then try again in that same position. The values should always be different each time you flip it.
now, pass that point back into TransformPoint and do the same method of debugging similarly, but this time you should get a world position which is always the same
so what I'm understanding by changing the sprite is that it attempts to use the world Y position as the object's Y relative position
what's happening here is that when you click the left of the box in world coordinates, it's translating to left of the box in its local coordinates
yeah its pretty much expected, howeverrr using global coordinates directly causes conflicts, i'll do changes and show what happens exactly
using inversePosition, this position in world coordinates should always become a position in local coordinates as to where you click
Better to question why you need to make each stat modular in design? Does every entity not have Agility?
Well, my thought was that npc's and players would potentially, but there might not be enemies that would have it. That idea then sprouted into; how can I drop in/drop out the stats
It just seemed like that would be a more robust system (Which I'd like to design)
That's fine, the only problem I can see is that you have to consider formulas later on as if you were to say attack someone and agility represents their chance to dodge, how will you handle those without agility? You would have to always check what you are attacking has agility, and if they don't then fall back onto another method.
Dragging rigidbody from Point
This is the precise thing I thought of when I realised my system was flawed, haha...
That IS something I'd like to do, e.g. weapon type, armour type etc.
But I realised my base design is too pidgeon holed, I just don't know what a good way of doing it is, am open to suggestions 😦
I've made stat systems such that if they are a caster then they have stats related to casting. They have spell damage, Mana, spell range, ect. But, when it comes to base stats like defenses, usually all my entities had it.
Interfaces like ICaster, IMelee, IRanger
otherwise I'd just give everything stats so I wouldn't have to fallback onto scenarios where they didn't have stats to compare against.
I did think interfacing might be a good way to handle it, but would you just have a script for each stat, and then that manages interactions that way?
Also; How do you assign that status to say, an entity? With a manager script
This is where my understanding is failing I think
The data structures i'm fine with, I just don't even have examples of these interacting with eachother
Well, first off I'd make an SO for each enemy and assign what they can do. Your method with this design would be composed of a list of stats each of these entities would have. My method of grouping stats a bit more would be a few fields that detail that if they are a caster I would assign a struct/class of stats relating to that.
[Flags]
public enum Affinities
{
None = 0,
Caster = 1 << 0,
Melee = 1 << 1,
Ranger = 1 << 2,
}
public class EnemySO : EntitySO
{
[field: SerializeField] public Affinities Affinities {get; private set;}
[field: SerializeField] public BaseStats BaseStats {get; private set;}
//Offensive Stats
[field: SerializeField] public CasterStats CasterStats {get; private set;}
[field: SerializeField] public MeleeStats MeleeStats {get; private set;}
[field: SerializeField] public RangeStats RangeStats {get; private set;}
}```
Ah, I see
Each of these being their own script with itneraction code, like you mentioned right?
Or are they lists which you set in each entity? because isn't that frequently re-used, even if just interfaces?
[Serializable]
public class CasterStats
{
public float SpellDamage;
public float CastSpeed;
public float Mana;
}```
Ah, I was going to suggest to check if these classes are null, but Unity will always create them regardless if you edit their instance in the editor, so what you can do is have flags or my preferred way of doing it with a flag enum
[Flags]
public enum EntityAffinities
{
None = 0,
Caster = 1 << 0,
Melee = 1 << 1,
Ranger = 1 << 2,
}```
if(EnemySO.EntityAffinities.HasFlag(EntityAffinities.Caster))
There is support for them in the inspector which is surprising.
Flags? Very cool
Maths question - has anyone done ellipse to ellipse intersection tests?! I am struggling to find C# code, I could use a general intersection maths library
I know Freya has a math one, not sure if it contains what you need though. Can check it out
https://github.com/FreyaHolmer/Mathfs
Nice, I think she skipped Ellipses though!
I think they may be missing rotation there which is my unfortunate need. I shall find it but it may be over complicated!
math.stackexchange.com looks very useful, unfortunately my understanding of equations is not amazing
seems you make one a circle and... https://math.stackexchange.com/questions/864070/how-to-determine-if-two-ellipse-have-at-least-one-intersection-point
but converting equations to C# is a problem for me!
hmm seems an n sided polygon might be the reasonable maths fix rather than such accuracy
Hey there mates, Im trying to cull particle system when offscreen, all is setup as recommended, but still not working (the PS still running even when cam is not showing the object):
The scene camera counts as a camera in this scenario, so you can't observe the pausing directly.
Hey guys, quick question. I'm using the navmesh system to move my player, and i did the boot logic for my game in a way where i create my player in a different scene from where my gameplay actually happens.
So.. there is no navmesh whenever i create my PlayerCharacter, how can i go around that problem?
Oh, so there is no way to observe the culling effect?
Not directly, but depending on what your particles are doing, you should be able to see that it is in fact paused while you're not looking at them.
through script and log?
If you have a particle system that is a burst emission that goes off every 5 seconds, and you look away right as a burst starts, wait 2 seconds and then look back, you should see that the same burst is still finishing, even though it should have finished in those 2 seconds.
Oh gotcha! Nice nickname btw, thats rare, lol
But through log it seems to be playing even off playmode cam/scene cam 😦
I don't think that property reflects whether it's paused from the culling mode. That's separate.
When it is doing culling, it doesnt pauses the ps ?
I did that:
if (_particleSystemOne.isPlaying)
{
Debug.Log(gameObject.transform.parent +" - "+ _particleSystemOne + " - is playing");
}
there is a way to check if culling is working through script?
Are you just doing this temporarily to make sure it's actually working, or do you need this to make your game work?
You can check if the renderer is visible through ParticleSystemRenderer.isVisible. Or you can check if ParticleSystem.time is still increasing. If you have the culling mode set to Pause, the time should stop. If it's set to PauseAndCatchup, it might either just keep going or pause and then jump when visible again.
Hello!
I have a base abstract class Fruit.
I have children classes, Apple, Banana and Orange, each with different parameters to change.
I want an editor that can select one of the children classes of Banana from a dropdown and use that class's field editor.
For example, I have a List<Fruit> fruits, and in the editor I add a new element. It shows a dropdown, and once I select class Banana, it allows me to change the parameters of that Bananaobject; when I find it on the code, I can cast that Fruit object to Banana and use its parameters.
How would I do this?
before I try to build there is no error, after I build it sends me the eror shown in the vid, it isnt even right since the game plays fine and the error is wrong wince I have a script with the name shadowcaster blah blah
You need to make a custom editor.
I'll ask there. Thanks!
Your if UNITY_EDITOR directive will make it only available in Editor.
do you guys use chatgpt as aid
no
im having an issue in my prototype
where animations for my player stay stuck in idle when looking at a large crowd of enemies
sorry if this is not the appropriate channel as the issue is not code related, but in the footage you can see stutters in the animation that happens when you look towards a large crowd of enemies (there are many more enemies hidden behind the wall)
if i look at them the animation gets stuck to idle
which animation?
the player's?
Also isn't this a #🏃┃animation topic?
yes
ill try posting it there
any1 know what is the error in the "get"?
you can't have two gets
look at the other ones and compare.
Just an unrelated FYI C# convention is for your type names (e.g. tile and tillcell should typically be PascalCase, not lowercase)
uhhh
how do you paste code in discord and make it look like actual code if u get what i mean
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I want to make an input record/replay system. Two questions:
- Can I simply use Update() to record/replay the inputs? Or would that cause issues because Update() is framerate-dependant?
- Is the Physics engine 100% deterministic? Or is there also some framerate-dependancy?
any1 know what is the problom?
error show
Suppression State
Error CS1061 'tillcell' does not contain a definition for 'coordinates' and no accessible extension method 'coordinates' accepting a first argument of type 'tillcell' could be found (are you missing a using directive or an assembly reference?)
- No. You should use some kind of fixed-interval system.
- It is deterministic but only on the same hardware. No framerate dependency, just hardware dependency
ok i will try to do this once more
Sems pretty clear. tillcell doesn't have a coordinates field but you're trying to use it.
how do i generate vector points for bezier curves
Hi im having an issue with my interactoruimanager class which basically manages the interface that allows u to interact with nearby interactable objects, the issue is that, the function executes fine and well, except that the SetActive part
it only works when theres an interactable within range but in this context it doesnt for some reason
public void PopUpTheInteractorUI(Vector3 position, string name, string type)
{
Debug.Log("trying to pop");
/* This is so that this function doesnt get called more than once after being called since its actively being called by an update function in another script that only activates when an interactable object is near the player
*/
if (hasPoppedUp)
{
Debug.Log("pop fail");
return;
}
hasPoppedUp = true;
/* the interactor is a class that i made which is basically a canvas in world space that acts as an interact interface and appears above item near to player
*/
interactor.gameObject.SetActive(true);
// position works fine, but for somereason, the interactor doesnt activate
interactor.gameObject.transform.position = position;
interactor.SetPopupInfo(name, type);
Debug.Log("pop success");
}
own code only no libraries
how its supposed to look
The math is on Wikipedia: https://en.wikipedia.org/wiki/Bézier_curve#Specific_cases
tyvm
so are the logs working?
yes
everything works
except the setactive part
so its staying inactive ?
yes
are you positive interactor isn't changed to inactive anywhere else
yes it is but i put specific conditions for it
if theres no interactable
show that part
it deactivates
sure
Any1 know what is the problom?
sry for too much probloms
is tile a monobehavior
read the errors, they tell you whats wrong
You need to read the errors my friend
seems you're mixing a custom Tile with Unity's Tile
Looks like tileprefab is tile but you're trying to put it in a Tile variable
did you make 2 different tile classes
this is clearly telling you the problem!
I would step through code to see if this is being called right after
in the update it checks for the nearest interactable object and in the second method it decides whether to activate the object or not
would doing some async magic solve things
if i manually activate the interactable then walk away, it naturally fades away
the fade away works
just not the appearing
the fact that its in Update is a little worrysome
i think that might be the issue
idk how to do it otherwise
code doesn't lie, if its staying inactive it is constantly setting to active-false
i made debug logs and all of them work fine
can you send the part on how you find interactable in the first place ?
ok
second pic is for the interactable class
basically if the player is near it
it added itself to the list containing all near objects to the player
then the player class does the maths and finds the closest one
i didnt use overlapsphere to save some performance i think
first pic is how to find the closest interactable
the FadeAway part is fine, its the conditions that call it that arent
the second part might be some spaghetti coding
do you have any suggestions
ill try doing async black magic otherwise
don't think async would change much here except add more complexity where it doesn't need to be
btw theres a single bool controlling the popup in the interact ui class
if object is activated once
bool becomes true
cant activate again
you need to find the condition to reset the whole system, I usually do a raycast so typically in the else statement is where I put it, but since here its a distance check its a bit more tricky
only by disabling the ui can you reactivate
the distance check works very fine
woah that image already tells everything about curves
yeah I understand that part, I'm just wondering, which condition you want so it is no longer interacted with
just increasing point on first line and second line by same % right
when theres no more item near you (no more interactables in the list), the object fades away
why not put the fade there then ? but only do it if there was interactor in the first place
like here
I see you tried something like that here already
ill retry that
what was wrong with it
i forgor
just make sure you check if interactor is not null
ah yes the issue was that in the second method which decides whether to show the ui or not there were some conflicts
ill try tweaking it
if interactor is null we exit the function
so everything below that line of code is the else statement basically
dont need to exit the whole thing, just the part of the UI. the return is fine, just put FadeOut inside the if interactor is not nulll
Not sure if this question should be here or in #archived-code-advanced,
I have a modual avatar that i'm merging at runtime into a singular skinned mesh. the outcome mesh looks fine but it does not render in unity.
what would be your starting point to investigate the issue? I am starting from a new mesh() so i might be missing some default setting
oh youre talking about the ui?
the Popup right?
yes
yea DeactiveInteractorUI
nothing changed unfortunately
if i deactivate all codes for the fadeout
the appear works again
lol
but i dont know where the contradiction in my code is
DeactivateInteractorUI being in Update
probably
where can i put it
yo , have no clue on how to do that any helpp?
tried fix that
technically that would be still called in update?
i cant
if its inside a method thats called in update
thats why Im saying remove it from Update you dont need it
all the code
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UIElements;
public class Tile : MonoBehaviour
{
public Tile state {get; private set;}
public tillcell cell {get; private set;}
public int number {get; private set; }
private Image background;
private TextMeshProUGUI text;
private void Awake()
{
background = GetComponent<Image>();
text = GetComponent<TextMeshProUGUI>();
}
public void Setstate( Tilestate state , int number)
{
this.state = state;
this.number = number;
}
}
tilestate CLASS
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "tile")]
public class Tilestate : ScriptableObject
{
public Color backroundcolor;
public Color textColor;
}
use the correct type for your variable
do you have any example
big reason you should not Name classes the same names as Unity classes 😛
its confusing you and your IDE (code editor)
Why are you posting this code that has nothing to do with the error
knowing if the count is 0 would require an update wont it?
in a distance check, correct
but ideally you would only run it once, since you only have closestInteractor once
closestinteractor dynamically changes
also. you should store these inside a variable, especially if you need to use it more than once
youre right
you're overcomplicating it. @hardy barn
You have:
B thing = whatever;
A otherThing = thing;```
You can't store a B in an A variable.
You would need:
```cs
B thing = whatever;
B otherThing = thing;```
no wait also curved line goes under the percentage
it changes but its either null or not null
so you're only fading if its not null and count is 0
so the null check is not necessary and i can only rely on the count?
null check is useful so you dont try to fade something that isn't there
since it occurs every frame and == 0
ah
closestinteractable is not UI
its an object that you can interact with
my naming convention is kinda bad
thats not what pops the UI ?
the UI itself is a singleton instance
closestInteractable is the closest interactable object to the player,
InteractorUIManager handles the worldspace canvas higlighted in red
those are the ones not popping up because ur hiding the UI everyframe
did i understand that?
it only hides the ui when theres no object
ill do a little tweak brb
the fading out works fine but fadein doesnt
thats the only issue
it doesnt fade in technically it just gets set active
i plan to tween it when it actually works
ok but its not being active because the setting to active false is running every frame yes?
so the problem is SetActive(false) running everyframe
i made a bool switch so getactive doesnt get triggered every frame
it only gets setactive false when the list is empty
and the debug logs prove that
my theory is that the update is so fast that it gets triggered before the first check idk
quite possibly
this is why im thinking of using an async method
that waits after the distance check to execute the second method of showing the ui
@rigid islandnvm i fixed it
literally all i did
was remove 1 bool
LOL
i used the bool bcs
i didnt want the tween to be called more than once
as u can see in the commented tween part
this is a nightmare for me
ohhh
do u know how to properly do it with tweening
you're talking about DOMove part?
yep
You could potential make a bool that gets back to false when the tween is comeplete
kinda how you had it before commenting
i have an idea of how ill try it
you can use the same way with the lambda function but with a bool
the OnComplete part
shouldn't that be !haspoppedUp
its supposed to be if (!haspoppedup)
yes youre right
the tweening words but only when i go far from the object
distance check conditions?
what was it ?
i forgot that i put a resetter here that resets the value of haspopped up to false
Ahhh
in the end it still only appeared when i got far from the object
and i accidentaly crashed my unity trying to fix with a while loop
wild
yeah while loops can do that easily lol
tweening is the most rage inducing thing 4 me
Hello! I'm having some problems with a glitchy rigidbody that I'm trying to move... It's like jittering everytime move the player, altrough the player doesn't seem to be jittering when comparing to the background. The jittering only occurs when walking, not when looking around so that the object follows. I'm kinda out of ideas as for what could be the problem, so all help is appreciated!
Here's the logic for walking:
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
direction = Vector3.zero;
direction = (transform.right * x + transform.forward * z).normalized * speed;
if (controller.isGrounded)
{
yVelocity = 0;
if (Input.GetButtonDown("Jump"))
{
yVelocity = jumpForce;
}
}
yVelocity += gravity * Time.deltaTime;
direction.y = yVelocity;
controller.Move(direction * Time.deltaTime);
}
And the logic for making the cube follow the crosshair when picking it up:
public void Update(){
if (isInteracitng)
{
pickupPoint = Camera.main.transform.position + Camera.main.transform.forward * pickedUpDistance - pickupOffset;
rb.velocity = Vector3.SmoothDamp(rb.velocity, (pickupPoint - transform.position) * smoothForce, ref refVelocity, smoothTime);
}
}
Also a video demonstrating the problem:
did you try putting it in the fixedupdate method
^^ ideally you want to move rigidbodies in FixedUpdate
Input should however be captured in Update
Tried now, still doesn't fix it...
also is Interpolation on
i think it might be related to the smoothtime in the smoothdamp?
more than likely is physics rigidbodies move at FixedUpdate and CharacterController is moved on Update
That seems to have fixed it, thanks!
i believe Tween is the type yes
https://dotween.demigiant.com/getstarted.php
had to double check
what could be a reason for killing the tween
I haven't explored dotween too much, i'm gonna assume its kind of like Coroutine?
maybe the object was disabled/destroyed or Timescale?
nah the object is still in the hierarchy and the timescale is 1
i fixed it by adding this lol im stupid
now it works FINALLY
after 3 days
thanks
nicee catch!
https://gdl.space/uqonogehek.cs is this the right way to use the new input system? I seem to be having issues when pressing two of the same keys at once.
No
First off - #🖱️┃input-system
but this is a rabbit hole I've been down many times, and trust me it's 10x simpler if you just make 10 separate actions
Skill1
Skill2 etc
Look how world of warcraft does it
imagine writing code to make this UI
With 10 actions, much easier
alright
Depends which workflow you're using but like
InputActionReference[]``` works
check the code to see
ah okay, then just index by which button
also, is action type "value" and control type "any" for something like this?
Why not Button
no clue
Again I'm recommending making 10 separate actions, each one a regular Button action
kk
also, is the OnEnable and OnDisable correct? it works but seems kinda messy
Not sure what you mean by that
in the code
is it correct to
//abilityAction.action.Enable();
//abilityAction.action.performed += ctx => TryUseSkill(Array.IndexOf(controls, ctx.control));
You'd have to be more specific. There are many ways to use the input system
im going to change the index stuff
is that the correct way to subscribe and do I need to enable/disable
someone was saying earlier that its wrong
even though it works
sure - if you use an array you can do like:
for (int i = 0; i < abilityActions.Length; i++) {
int actionNumber = i;
abilityActions[i].action.performed += ctx => TryUseSkill(actionNumber);
}```
If you want to unsubscribe you just can't use a lambda
is it necessary to unsubscribe?
That depends on whether the subscriber of the action has a shorter lifespan than the action asset itself
okay, so just to keep it clean, i dont use a lambda and instead subscribe/unsubscribe with a for loop
I don't thnik those are mutually exclusive
"If you want to unsubscribe you just can't use a lambda" am I misinterpreting?
since I am doing it in array, i dont need the ctx
well you either need an actual function (per action) or you need to store the lambdas in an array for later unsubscribing
True but you need the actionNumber
which is just the index
Sure but you can't pass that index into the function without a lambda or something else
Right, that's what I have told you yesterday
ah yeah
You will have to subscribe it to an actual method without adding the additional parameters
onSomethingHappenning += YourMethod;
onSomethingHappenning -= YourMethod;
yeah, do you recommend making methods for each skill or leaving it how it is? also, do I need to enable/disable the action as well ie abilityActions[i].action.Enable();
You can do something like:
Action<CallbackContext>[] lambdas = new[10];
// subcribe:
for (int i = 0; i < abilityActions.Length; i++) {
int actionNumber = i;
lambdas[i] = ctx => TryUseSkill(actionNumber);
abilityActions[i].action.performed += lambdas[i];
}
// unsub:
for (int i = 0; i < abilityActions.Length; i++) {
abilityActions[i].action.performed -= lambdas[i];
}```
you can do it that way or just enable the whole action map
btw yes the "actionNumber" thing is necessary due to lambda variable capture
You may disable an action if it shouldn't be invoked
private void OnEnable()
{
for (int i = 0; i < abilityActions.Length; i++)
{
abilityActions[i].action.Enable();
int actionNumber = i;
lambdas[i] = ctx => TryUseSkill(actionNumber);
abilityActions[i].action.performed += lambdas[i];
}
}
private void OnDisable()
{
for (int i = 0; i < abilityActions.Length; i++)
{
abilityActions[i].action.Disable();
abilityActions[i].action.performed -= lambdas[i];
}
}
look good?
Looking fine to me, but actionNumber is not necessary if it simply equals to i
actionNumber is necessary
otherwise you'll get lambda variable capture on the i variable
and all of your actions will act as if they use the skill at abilityActions.Length
Oh, right
And that's a fun bug to figure out down the road when it breaks 😄
My nemesis, Lambda Capture
Oh what a coincidence that I was just talking in #archived-code-advanced earlier about reactivity systems having the ability to automatically unsubscribe, and the internal mechanism essentially boils down to the exact same code.
I remember having the same bug almost a year ago. And now I'm telling them to get it too, haven't learned from the mistakes 
is there a way within the input asset to make it repeat while held or do I just handle that in code?
handle it in code
Are you using the new input system?
yes
Are you using C# events?
performed is invoked in Update every time the value gets changed
They're using new Input System's actions
Yup, which are c#, rather than unityevents off of playerinput component. Just wanted to be sure
only when the value is changed
void Update() {
if (myInputAction.IsPressed()) DoSomething();
}```
Right, what have I said?
wont that double press when I press once though?
The way I did it was with an internal timer started with on performed, and then incremented and checked either in update or in a coroutine or unitask
'new' input system doesn't have continuous callback so that would require to poll that input unfortunately
From the api
You said you wanted to do something every frame
Yes this is the way^^ those are like GetButton GetButtonDown, GetButtonUp
performed is a continuous callback
it only happens when the control actuation changes
that's just that frame, no?
if we're talking about a button, it's only when the button is pressed
if it's a joystick it's when the joystick changes actuation. It's not every frame.
It is called every time the value is changed
I know you can boolean continous callback though for when you pressed or release
on performed only gives continuous input if it's on a vector2 like a joystick and you don't keep it perfectly still
You can check the context value of button type and while it’s = to 1 do action
yep if you're just holding the joystick to the right, you won't get a performed each frame
full stop if you need to do something every frame you should be using Update
so i could just get rid of the subscribing and what not and just loop checking for IsPressed
private void Update()
{
for (int i = 0; i < abilityActions.Length; i++)
{
if (abilityActions[i].action.IsPressed())
{
TryUseSkill(i);
}
}
}
Having a WASD movement also calls it multiple times when the direction gets changed from (1, 1) -> (-1, 1) -> (0, 1)
I should update my central input handling class for held down buttons. I think I'll have other classes subscribe with an action to call whenever the designated button is kept held down for a minimum of X seconds, and then retriggered every Y seconds after
but you probably want WasPressedThisFrame() no?
unless you want TryUseSkill to happen every frame
hm, should I centralize input and have other classes just access that
ideally I want it to get pressed once when pressed, then after a short delay, repeated every frame
It depends how many other classes you have asking for input. If it's just a player controller and maybe one menu system, then probably not. If you got lots of different classes wanting input then centralizing it can save a lot of work
similar to holding a key while typing
okay, ill keep that in mind
One other benefit is that if you're doing lots of clean up or processing of the raw input before using it, then a central class can unify that all in one place
Or for things like a fighting game where inputs get parsed for special moves and you'd likely want that figured out in one spot, rather than your fireball code doing the work and then your piledriver code doing the exact same work, etc.
okay, its not going to be too complex so I don't think it's needed
It's not something that's too difficult to refactor into a single class, if you do find you need it, so no need to worry and do it prematurely
how can i approach this with scriptable objects
SOmething like:
public class Number : ScriptableObject {
public int val;
}
public class Addition : MonoBehaviour {
public Number a;
public Number b;
public int CalculateResult() {
return a.val + b.val;
}
}```?
unclear what you mean beyond this
i want something like a drop box for the sprite and this for the same time
like number A
So in game you drag one of those number blocks into the formula and it calculates it?
its like a crafting system but u just click a button
u dont drag in anything
Got it, you select the A you want, the B you want, and C changes
So the blocks wouldn't be numbers, but some kind of ingredient, item, resource, etc.
So you'd probably make a scriptable object that stores the data of those things
Another class for the clickable option that references which scriptable object is the data for it
And finally some overall class that tracks what options have been picked and determines the result once A and B are selected
Oh and probably a recipe class as a scriptable object which has references to A and B, and the C you get as a result
So that last class above goes through the list of recipes it has and finds the matching one to find C
Hi i am helping make a tool that allow people to cad robots spesificly for the vex robotics compation and we want to add a feature which would allow people to import diffrent 3d models for stuff like custom plastic parts and stuff like that, how would i go about doing that?
importing models at runtime, not in-editor, right?
ya
for glTF, there's https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@5.2/
Not sure about FBX.
anything for obj?
There are so many obj libraries that you'd need to see which fits your needs
thanks
I'm trying to make a folder that is ignored on specific build platforms. In a IPreprocessBuildWithReport interface, I'm trying to move Assets/Server to Assets/Editor/TempBuild, then in a IPostprocessBuildWithReport move it back. AssetDatabase.MoveAsset either gives me the error Destination path name does already exist or Destination parent directory does not exist, in addition to an error that says access is denied. I've tried several workarounds with AssetDatabase, but nothing has worked. Does anyone have experience with this?
No, there is no. And I don't really think you need it
Imagine setting both row and column count to 3 and having more than 9 elements in your group
If you still need it, you may write a script based on the Grid Layout Group to check when the child was added to the GameObject and remove it if needed
Right, let's say you want to have 4 columns and 6 rows.
Set the Fixed Column Count to 4 and manage the other logic via code.
Remove the oldest message just if the current messages count equals to 4 * 6 = 24
Hey all!
I'm trying to make a combat system, where the human will attack a pig and it will be knocked back, similar to Super Smash Bros
However, as you can see above, the knocback is not very good
I'm trying to understand the problem however it feels like I just am not handling it properly. I can't type out all the code at the moment until someone asks for a specific area of it, because it's handled by many functions.
this is my damage hitbox script however:
public GameObject parent;
public float allowedImmunityTime = 0.4f;
public AttackHitbox attackHitbox;
private float immunityTime = 0f;
[Header("Feedbacks")]
public MMF_Player DamageFeedback;
public void Damage(GameObject attacker, Vector2 knockback, float damageAmount){
if(immunityTime <= 0){
DamagePopupGenerator.current.CreatePopup(transform.position + new Vector3(Random.Range(-0.5f, 0.5f), Random.Range(-0.5f, 0.5f), 0f), damageAmount.ToString(), Color.red);
if(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x != 0){
parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x * knockback.x * 2f, attacker.GetComponent<Rigidbody2D>().velocity.normalized.y * knockback.y + knockback.y/4), ForceMode2D.Impulse);
}
else{
parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(Mathf.Sign(attacker.transform.localScale.x) * knockback.x, knockback.y), ForceMode2D.Impulse);
}
parent.GetComponent<Animator>().Play("Hit");
immunityTime = allowedImmunityTime;
DamageFeedback?.PlayFeedbacks();
StartCoroutine("ImmunityFrames");
}
}
private IEnumerator ImmunityFrames(){
while(immunityTime > 0){
immunityTime -= 0.01f;
yield return new WaitForSeconds(0.01f);
}
}
The main part where we add force is parent.GetComponent<Rigidbody2D>().AddForce(new Vector2(attacker.GetComponent<Rigidbody2D>().velocity.normalized.x * knockback.x * 2f, attacker.GetComponent<Rigidbody2D>().velocity.normalized.y * knockback.y + knockback.y/4), ForceMode2D.Impulse);
Where knockback is a vector2 I define with two arbitary ints that match as a multiplier, and I'm adding the attacker's velocity onto the attack for direction.
i feel like the direction vector between the two objects should factor into this too, basing it only on velocity looks weird imo
maybe add some minimum value to the y speed too, your animation looks like a powerful upwards swing and that's not reflected in the code at all
yeah! i fixed it up, thank you :)
Hey!
I'm trying to export a .gltf 3d model using Unity's GLTFast library and I came across this on the documentation. Any idea on what this means? I found the two assembly definition files but I dont know where to reference them
if your own code isn't inside an assembly definition you've made, you probably don't need to worry about this
I haven't touched assembly definitions before this but Unity says that The type or namespace name 'Export' does not exist in the namespace 'GLTFast' (are you missing an assembly reference?)
oh looks like the Export assembly has auto-referenced turned off, so it's not available in the default assembly for whatever reason
if you can't turn that on, then you would need to make your own assembly definition and add it as a reference yeah
Thanks! I just found a github repo of the package and imported that and removed the package manager version. THen I was able to tick the auto reference
Oh, by the way, is there a way for a Unity build to export a gameobject as a prefab so that another build could read it sometime later?
asset bundles, maybe?
yeah, asset bundles or addressables, which is asset bundles in a trenchcoat
my addressables journey has been confusing so far
especially with my lack of cloud understanding
you can use it without any of the cloud stuff if you don't need it
ok but what about exporting a bundle at runtime? and another build downloading and unpacking it? is that really possible?
if I have a script thats a component on a prefab but the script has been compiled on both builds, then would the references and other stuff transfer over via the prefab without any editor intervention?
oh at runtime? not really, prefabs don't exist at runtime
that would be more like a save system
I see
So this is the flow of my application
I import a 3d model, attach a script to it and tweak it a bit and reorder and reposition a few of the children in the 3D model. I have completed my project this far. Now I want to be able to package this gameobject (info about the transform of the GO, its children, the script that I attached to it and its values and references) along with the actual 3D meshes, the .glb . And I want to be able to load this package and get the exact same gameobject
both are builds of the same project
what part of this is happening at runtime?
All of it
I know bruteforcing it is an option
or atleast I hope so
put everything in a messy json and reconstruct it
you could look at formats other than json, but yeah you'll mostl likely need to serialize the data yourself, asset bundles won't work for this
Don’t use that
yeah, it might work but there's various reasons it's not a good idea
The reason why it works is the reason why you can’t (shouldn’t) use it
technically you can duplicate a prefab’s yaml and store that to exchange your structures together with the assets but you’d have to basically rebuild the Unity editor’s serializer and asset database for runtime usage.
Hmm I feel like this is almost impossible considering theres models of size of about 60mb involved
oh
It’s 100% not what unity is designed for though
agreed
BinaryWriter/BinaryReader are decent but you'd need to write a lot of the boilerplate serialization stuff yourself, i'd check out maybe protobuf of flatbuffers or one of those libraries
You will be fighting the engine at every turn
i use MessagePack but it's kind of fiddly to set up
I have a lot of errors of this form:
The .meta file *** does not have a valid GUID and its corresponding Asset file will be ignored. If this file is not malformed, please add a GUID, or delete the .meta file and it will be recreated correctly
Can I somehow automatically tell unity to remove all meta files with invalid guids, but keep the rest?
all ‘safe’ serialization is terribly annoying to use 😄
sorry if this sounds annoying but 😅
where would one go about beginning the serialization process
What’s typically done is embedding an interpreted language for runtime execution
and using that to do all of your asset/prefab export/import
i'm not sure how adding an interpreter helps with that 😅
that works with regular unity asset bundles since Unity treats it all as data, and this would allow you to include code in your assets
No scripts can be added via assetbundles
oh for scripts, yeah, if you need to add new scripts in a bundle
idk if chipe needed that
if you just need to save which existing scripts from the base game are on a prefab, that can all be done with any serialization library
yup
an interpreted language, maybe a DSL, would just be a replacement for a complicated API that these assets would need to use declaratively
It’s all a big yuck to develop though 🙃
there's lots of answers to this but i guess at some point you have to have a method like void Serialize(GameObject instance, Stream output) and the rest is up to whatever serialization format you're using haha
If you were using an engine where the# editor and runtime are the same app, it’d be a breeze to implement
is that why debug gizmos dont work in builds?
yes
But there are assets for that. You can still draw your own, but not through the builtin API
hmm I'll report to you once I get there
I am getting errors of the form
The referenced script is missing on Shooter Spawner (index 2 in components list)
However, I do not have a gameobject called Shooter Spawner in my scene
does anyone know how I could find the GO the error is talking about?
Isn't it a component?
"index 2 in components list"
Yes but a component on some game object
or actually I don't know
Well, yeah, you said "I do not have a gameobject called Shooter Spawner"
if shooter spawner refers to the GO name or component name
Well, this is definitely not a build-in component
Yes you are right, but in either case I'm not finding the corresponding GO :/
yes haha
You have a ShooterSpawner script. Find its references
Yes thats what I tried
but here is riders find-anything results - empty
let me maybe try find
I don't use Rider. Does it have "asset references" written above its class' name, as shown in the image I've sent?
And how don't you know about your own scripts? Do you have so many of them?
But no, there is no single file which has the word ShooterSpawner inside of it:
/Assets$ find . -type f -name "*.cs" -exec grep -l "ShooterSpawner" {} +
this returns nothing and should return all files
yeah ofc its quite a large project, I don't have them all in my head haha
but if neither find nor rider are able to find any file with ShooterSpawner in it, I don't think there is any file
Does this have the call stack?
You may also try finding it in Unity Assets
Ah actually, the error comes from a package I have installed
I'll ask the support there, maybe they are still using some old files or something
If it's a package you have installed, you can find the scripts in Packages.
I do not think its actually a GO. I now found more error messages of the form
The referenced script on this Behaviour (Game Object 'Shooter Spawner') is missing!
UnityEngine.Object:Instantiate<UnityEngine.GameObject> (UnityEngine.GameObject)
Rukhanka.Hybrid.AnimatorControllerBaker:ConvertAllControllerAnimations (UnityEngine.AnimationClip[],UnityEngine.Animator) (at ./Packages/com.rk.rukhanka/Rukhanka.Hybrid/AnimatorControllerBaker.cs:550)
I think it just has some old GO referenced somewhere and I do not fully know where, I'll find it though
Thank you for the help!
Right, that's probably the package's problem then
Good afternoon everyone
I have a question regarding in app purchases
So I'm pretty sure most of you know about Lucky Patcher, if not it's an app that bypasses your IAP and basically gives you free money
Is there a way to prevent Lucky patcher to not give free stuff and bypass your IAP? An example is Future Fight, the game is built on Unity however they don't let Lucky patcher bypass their IAP
Not really a Unity question. I googled it: https://stackoverflow.com/questions/13445598/lucky-patcher-how-can-i-protect-from-it
I apologise if it's not a unity question
But only reason I asked here is because I use unity to build my games and what not
Do note however with something like this it's a never ending and ultimately losing battle
Since the user physically owns their own device there's ultimately little you can do to prevent them from controlling the software running on the device, if they are sufficiently motivated
If it's a network enabled game you can get away with judicious validation and ownership of the data stores keeping track of user items and currency etc
I'm more of targeting the users who doesn't have knowledge on how to bypass such things without the use of lucky patcher, hence the majority of users
I'd make it a network enabled game but however I have little to no knowledge on how that works, I'm still studying it and once I do know how to do it I'll make it a network game
if enough people care, it only takes one person to write a new patcher for your game, then it's just as easy for everyone else
Someone can always make a cracked version of your app with everything purchased.
I have no evidence to back this claim up, but if you are making a single player game, people who are desperate enough to do these kinds of hacks, aren't likely the ones to ever purchase anything anyways.
Question about managing sound effects:
I began managing my sound effect files by creating an Audio Manager script that's applied to a game object which stores a list of my audio sources. I then reference to a specific file within other objects as needed.
I've read this may become an issue with memory as I'm loading all the files into the game, including the ones that may not be used in a specific scene.
Would it be better to apply the audio files to the objects that use them?
Dont try to optimize something that is not an issue yet. Release first then solve this 😉
Hello I'm trying to instantiate objects along specific positions and with correct rotation in script, but the pivot position of that object is on the corner instead of the center so when instantiated with a specific rotation like 90 degrees for instance, it rotates around the pivot point, therefore shifting the actual position. I tried to instantiate it in a parent to solve the problem but it still rotates around the pivot point. Can anyone point me in the direction to solve this issue
parent.transform.position = position;
Bounds bound = GetPrefabBounds(building[0]);
Vector3 pivotOffset = position + new Vector3(bound.size.x / 2.0f, 0, bound.size.z / 2.0f);
Instantiate(building[0], pivotOffset, Quaternion.Euler(0, Yrotation, 0), parent.transform);
parent.transform.DetachChildren();
Destroy(parent);
Hey I'm back
Why not just fix your prefab's pivot
Is it hard to do?
I have a huge amount of them and tought it would take a lot of time
I managed to build somewhat of a serializer for a gameobject and I've covered Mesh filter and transform components @cold parrot @thick terrace
But now the problem is parsing through all the children in the GO and then instantiating then all at once is taking a toll on my performance. How do I fix this?
Also stuck on materials
This is what I've come up with but the material part is still very errory
load screen and cache em
Well unless you fix the pivot points then you have to be able to specify the point you want to rotate around specifically.
Do you know around which point you want to rotate it about? Because if you do then just specify the axis in this method and you are done https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
unity prefabs have the advantage of being deserialized on a background thread so you could look at doing the same thing, otherwise if you can't cover it up with a loading screen, you could write it as a coroutine and yield between the expensive operations and/or every x elapsed milliseconds to split the operation over several frames
The shifting problem happens because the rotation is being applied after translating for the offset, which still causes rotation around the original pivot point of the object.
It takes less than 2 seconds for a model with 1.5M vertices and 7 materials to be recreated. apparently mesh serialization was what took so long, Holo-Lens put out a samp,e unity project where they used a mesh serializer which was what reduced the 2 minute load time to 2 seconds 😁
You must search by GUID, not name
Unity does not care about asset names.
I found the error now. It was actually not a component, but gameobjects of that name
I grep for GUIDs fairly often. It's more reliable than Unity's own "find references"...
usually when i'm seeing if i can delete an asset
I found them using find/grep by searching all files for Shooter Spawner instead of ShooterSpawner
they were in a .prefab file
Ah, I see!
then I checked that prefab and saw that it has deactivated child gameobjects which reference those scripts
I have many areas in my code that require themselves to be updated a little bit to accomadate whenever I had a new weapon type. Are there are programmer techniques or VSC extension that will make it easier to track these. They will be in multiple different files
What kind of changes?
Ideally, you would write code in a way that the compiler does it for you, by causing compile errors unless you have properly implemented things.
Has anyone done an inverted mask for UGUI? struggling with examples
alternatively, the design needs to be changed so that new kinds of weapons don't require you to rewrite so much existing code!
the whole open-closed principle
Is there a better way to detect that the game has changed screens than constantly comparing the current list of resolutions to an old list of resolutions?
I need to update my settings menu when this happens
but this is emitting a lot of garbage
I'm pretty sure Displays.onDisplaysUpdated does not fire when this happens
(it's not even in the documentation!)
Basically I have 3 weapon types: Repeater, Ballistics, Cannon. If I add another called... Beam it will not choose the right set of stats until I manually update weapon logic to include it
How are your code currently structured? That sounds like a design issue.
One way to do it is to have the stats on the weapons themselves, eg a Weapon base class or an IWeapon interface that has Stats property.
Whatever that needs the stats would just do currentWeapon.Stats to get it, it would not involve updating any code.
Probably I'll thread the code here:
Or not clyde says no
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
[CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
public class WeaponObject : ScriptableObject
{
#region Variable Declaration
[Header("Visuals and Information")]
[Tooltip("Make sure the model is a PNG and has been set to Point Rendering")]
public Sprite model;
public new string name;
public string description;
public enum weaponType { Nothing, Repeater, Ballistic, Cannon }
[Tooltip("Here you can specify the weapon type which will change the stats it uses.")]
[SerializeReference]
public weaponType type;
[Header("Weapon Stats")]
public RepeaterStats repeaterStats;
public BallisticStats ballisticStats;
public CannonStats cannonStats;
#endregion
}
#region Weapon Variables
[System.Serializable]
public class RepeaterStats
{
public int maxChargedAmmo;
public float laserDamage;
public float lasersPerMinute;
public float dropoffDistance;
public float chargingSpeed;
public GameObject projectile;
}
[System.Serializable]
public class BallisticStats
{
public int maxBallisticAmmo;
public float bulletSpread;
public float bulletDamage;
public float bulletsPerMinute;
public float heatLimit;
public GameObject projectile;
}
[System.Serializable]
public class CannonStats
{
public int maxCannonShells;
public float shellDamage;
public float reloadTime;
public GameObject projectile;
}
#endregion
This is the code for the weaponObject itself. Each class is belonging to a different weaponType
void Start()
{
playerControls = new PlayerInputs();
playerControls.Enable();
weaponType = weaponData.type.ToString();
// Make changes to this as new weapons are added
switch (weaponType)
{
case "Repeater":
fireRate = 60 / weaponData.repeaterStats.lasersPerMinute;
break;
case "Cannon":
fireRate = weaponData.cannonStats.reloadTime;
break;
case "Ballistic":
fireRate = 60 / weaponData.ballisticStats.bulletsPerMinute;
break;
}
}```
sorry other poster 🙏
@versed spade Use paste sites to post large blocks of code !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Display.main doesn't change when you move the game from one screen to another, so that doesn't help.
Ok, I remember discord had some sort of in-app code block thing that shrunk it. Is it gone or am I using it wrong?
ah 😦
use a paste site
will try
to the one who delete their question
i think it is nearly impossible to get a non axis-aligned bounding box (call it NAABB below
consider a triangle, there is only one AABB of it, but for NAABB you can have 3 (if you make the NAABB aligns one of its side)
So, I'm screwed, sad 
Thanks for the info
you can compute a bounding box in an object's local space
ofc you can somehow define its "major axis" then for all other vertices, get their distances to the axis and bound it
ah, compute (get) the AABB in local space then rotate it
Ah, I can get Screen.mainWindowDisplayInfo, which does change when the window moves from screen to screen.
and I can then check if the height/width/refresh rate/name changed
this allegedly produces no garbage
grumble. 42B allocation.
actually that will be 64 bytes, grumble, mumble, grumpy old man nit picking
ah, it's an Editor-only allocation
Yoooo what's happened?
Can't open project after making copy of project for github repo path
also can't exit from safe mode ☠️
I have a missle and a mesh with other objects like trees and stuff. I want the rocket to rotate to avoid the obstacles and mesh. However this code just doesnt work and im confused why
Anyone?
ah, your rotation is backwards
do transform.rotation * ...
Q1 * Q2 is the result of applying Q1 followed by Q2
huh?
Quaternion avoidanceRotation = Quaternion.FromToRotation(transform.forward, -surfaceNormal) * transform.rotation;
oh this line?
Quaternion multiplication is not commutative: A * B != B * A



